Hi python fans, hope someone can help me with this.

I have a text file the result of another program which looks like:

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

This may vary in size but will always be square i.e. 5x5, 9x9 etc so the code needs to accomodate this, the maximum ever size will probably be 12x12.

I want python code which will read in the text file and store it in a way I may then access each individual number.

Thanks in advance, assistance appreciated in the meantime I'm off to try and crack it and if I find out first then I'll post back.

You can take a look at this code.
Python also have a CSV module

my_list = []
with open('my_csv.txt') as f:
    l = [i.strip().split(',') for i in f]
    for i in range(len(l)):
        my_list.append([int(n) for n in l[i]])

print my_list
print my_list[0][1] #Take out a number
print my_list[-1]   #Take out last line of numbers

"""Output-->
[[2, 6, 3, 5, 0], [4, 0, 2, 5, 2], [5, 7, 9, 1, 0], [4, 6, 8, 2, 5], [2, 7, 9, 1, 6]]
6
[2, 7, 9, 1, 6]
"""

Edited 5 Years Ago by snippsat: n/a

Thanks for the response, I needed to maintain the text file in its format and managed to achieve this and a count of lines with:

array = []

file = open('filename.txt')
for line in file.readlines():
	line = line.split(',')
	array.append(line)

i = len(line)

file.close()

In python call it list not array.
This line in my code and you have number of lines.
print len(my_list)

Edited 5 Years Ago by snippsat: n/a

This article has been dead for over six months. Start a new discussion instead.