-2

i have a text file like this

.txt

1, 2, 3, 4, 5, 6, 7, 8, 9

and i would like to view this as an array in python this is what i have so far

python file

file_board = open('index.txt')
board = file_board.read().split(',')
print board
print len(board)

output

['[[1', ' 2', ' 3]', ' [4', ' 5', ' 6]', ' [7', ' 8', ' 9]]\n']
9
list index out of range

so what i want todo is some how make this in to a 2D array for manipulation

Note I would like to do this without any external libraries, build in libraries are fine

by the way i would like to write this back to a new file in the format of

1, 2, 3, 4, 5, 6, 7, 8, 9
7
  • welcome to SO! have a look at this post, i think it has the answer you want: stackoverflow.com/questions/7163024 Commented Dec 13, 2018 at 21:15
  • updated my question @slider Commented Dec 13, 2018 at 21:20
  • updated my question @MCO Commented Dec 13, 2018 at 21:20
  • updated my question @AuroraWang Commented Dec 13, 2018 at 21:20
  • Your output and the text file are inconsistent. If your text file was really how you say it is, the output would just split at every comma, producing [1,2,3,4,5,6,7,8,9]. Commented Dec 13, 2018 at 21:24

2 Answers 2

1

@dlink's answer is OK, but to be safe you may want to use ast.literal_eval to prevent security issues:

import ast

file_board = open('index.txt')
board = ast.literal_eval(file_board.read())
print board
print len(board)
Sign up to request clarification or add additional context in comments.

Comments

-1
str = '[[1, 2, 3], [4, 5, 6], [7, 8, 9]]'
data = eval(str)
for rec in data:
    print rec

Output

[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

If you want a 2D array (You edited your question). You can use regex to remove the '[' and ']' and spaces.

import re
str2 = re.sub('[\[\] ]', '', str)
print str2

output 1,2,3,4,5,6,7,8,9

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.