Frage

I need to be able to read characters (numbers) from .txt file and use them in tkinter rectangles coordinates. So basically I need to get these numbers stored in some variable to be able to work with them. Anybody?

I've tried to do this:

myfile = open('vystup.txt')
c = myfile.read(1)

which works fine but I would like to read numbers like 300, 45 and no just 3, 5, 6 etc.

my txt file looks like:

45 66 786 44
3 17 5 400
57 88 9 80 4

and the best solution will be to be able to store numbers from each row to different variable. but I suppose this should be easy anyway.

I've also found this here on stackoverflow:

a1 = []
a2 = []
a3 = []
a4 = []

with open('vystup.txt') as f:
    for line in f:
        data = line.split()
        a1.append(int(data[0]))
        a2.append(int(data[1]))
        a3.append(int(data[2]))
        a4.append(int(data[3]))

but this works for columns not rows. Anyone who can change this code to rows instead of columns?

War es hilfreich?

Lösung

As doc says:

For reading lines from a file, you can loop over the file object. This is memory efficient, fast, and leads to simple code

There is an example also about looping over file object.

Assuming your input is like

45 66 786 44
3 17 5 400
57 88 9 80 4

This code will put every number to a list. Then you can access them from those lists as you wish.

with open("numbers.txt") as f:
    for line in f:
        print  (line.strip().split()) #strip removes newlines and split, does splitting. 
                                      #if you give split an argument it will split  
                                      #respect to that instead of spaces

>>>
['45', '66', '786', '44']
['3', '17', '5', '400']
['57', '88', '9', '80', '4']

Andere Tipps

If you need to parse these values as integers, it would be useful to save these numbers as an array; let's do it this way:

var_array=[]
f=open('vystup.txt')
for line in f.readlines():
    # read line, split it on spaces, and append them as integers to var_array
    var_array.append(map(int,line.split()))

# now you have array of integers:
print var_array
>>> [[45, 66, 786, 44], [3, 17, 5, 400], [57, 88, 9, 80, 4]]

# having it, you can iterate through var_array 
# selecting columns needed in your code; 
# for example, get only first columns from your array:

for item in var_array:
    print item[0]

>>> 45
>>> 3
>>> 56

etc.

Of course I made an assumption that all the values in file are integers.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top