-3

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
umläute
  • 28,885
  • 9
  • 68
  • 122
o3192057
  • 1
  • 2
  • 2
    what is the difference between your new file and your old file? – d_kennetz Dec 13 '18 at 21:33
  • 1
    are you sure you get the output as described? (it should be `['1', ' 2', ' 3', ' 4', ' 5', ' 6', ' 7', ' 8', ' 9\n']` instead). You also might start writing `print(foo)` instead of `print foo`, as the latter notation is no longer valid in Python-3 (and Python-2 will [not be maintained past 2020](https://pythonclock.org/) - start writing Python3 code *now*) – umläute Dec 13 '18 at 21:36
  • i would do some calculations and change those numbers later on @d_kennetz – o3192057 Dec 13 '18 at 21:41
  • but they are already in that format, .txt literally looks the exact same as your last line – d_kennetz Dec 13 '18 at 21:43
  • Do you want an `array` or a `list`? – Jan Christoph Terasa Dec 13 '18 at 21:53

1 Answers1

0

You could do it like this using index slicing and zip:

infile = open('./Desktop/nums.txt')

board = infile.read().strip('\\n').split(',')
# the numbers are in string format at this point
# board ['1', ' 2', ' 3', ' 4', ' 5', ' 6', ' 7', ' 8', ' 9']
board_array = [[int(x),int(y),int(z)] for x,y,z in zip(board[::3], board[1::3], board[2::3])]

output:

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

I do not understand what you want from your output but this will generate a 2D array of ints from your text file and it will strip that new line character '\n'

d_kennetz
  • 5,219
  • 5
  • 21
  • 44