python - Import txt file and having each line as a list -
i'm new python user.
i have txt file like:
3,1,3,2,3 3,2,2,3,2 2,1,3,3,2,2 1,2,2,3,3,1 3,2,1,2,2,3
but may less or more lines.
i want import each line list.
i know can such:
filename = 'myfile.txt' fin=open(filename,'r') l1list = fin.readline() l2list = fin.readline() l3list = fin.readline()
but since don't know how many lines have, there way create individual lists?
do not create separate lists; create list of lists:
results = [] open('inputfile.txt') inputfile: line in inputfile: results.append(line.strip().split(','))
or better still, use csv
module:
import csv results = [] open('inputfile.txt', newline='') inputfile: row in csv.reader(inputfile): results.append(row)
lists or dictionaries far superiour structures keep track of arbitrary number of things read file.
note either loop lets address rows of data individually without having read contents of file memory either; instead of using results.append()
process line right there.
just completeness sake, here's one-liner compact version read in csv file list in 1 go:
import csv open('inputfile.txt', newline='') inputfile: results = list(csv.reader(inputfile))
Comments
Post a Comment