-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
martineau
  • 119,623
  • 25
  • 170
  • 301
o3192057
  • 1
  • 2

2 Answers2

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)
miike3459
  • 1,431
  • 2
  • 16
  • 32
-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

dlink
  • 1,489
  • 17
  • 22