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.

Recommended Answers

All 3 Replies

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]
"""

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)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.