简体   繁体   中英

reading values from a text file and storing it into lists

I have values in a text file which will be like this for example:

1,2,3,4
1,1,1,1
4,3,2,1
2,2,2,2
   ...etc

now i want to store each line into a list and thus, i have created a list of lists to store these values

numbers = [[]]

how would i go about storing these values into the list so that from the example aboe:

numbers[1] = [1,2,3,4]
          ... etc

so far i have this:

    with open(s) as f :
    for s in f:
        numbers = [l.split(',') for l in f.readline()]

but i am unsure if this is the correct way to do it, or if there is better way to do it

Thanks in advance for the help

You should cast your input as int. Also, you can do it as a one-liner:

with open('test.txt') as f:
    numbers = [[int(j) for j in i.split(',')] for i in f.read().split('\n')]

>>> print numbers
[[1,2,3,4],
 [1,1,1,1],
 [4,3,2,1],
 [2,2,2,2]]

You can use the csv module with a list comprehension and/or map :

import csv
with open('text1.txt') as f:
    numbers = [map(int, row) for row in csv.reader(f)]

>>> numbers
[[1, 2, 3, 4], [1, 1, 1, 1], [4, 3, 2, 1], [2, 2, 2, 2]]

For Python 3 you'll have to add an extra list call around map or use a list comprehension(Will work in both Python 2 and 3):

numbers = [list(map(int, row)) for row in csv.reader(f)]
#or
numbers = [[int(x) for x in row] for row in csv.reader(f)]

Without importing any module you can do:

>>> with open('text1.txt') as f:
    numbers = [[int(x) for x in line.split(',')] for line in f]
...     
>>> numbers
[[1, 2, 3, 4], [1, 1, 1, 1], [4, 3, 2, 1], [2, 2, 2, 2]]

Here as you can see you need to iterate over the file object not file.readline , iteration over a file object returns one line at a time, and then we split that line and case its items to integers. ( file.readline() only returns one line, and in your code you were only iterating over that line, which is wrong.)

rows = []
with open("foo.txt") as f:
    rows = [l.split() for l in f]

Output

[['1,2,3,4'], ['1,1,1,1'], ['4,3,2,1'], ['2,2,2,2']]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM