Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import txt file and having each line as a list

I'm a new Python user.

I have a txt file that will be something 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 be less or more lines.

I want to import each line as a list.

I know you can do it as such:

filename = 'MyFile.txt' 
fin=open(filename,'r')
L1list = fin.readline()
L2list = fin.readline()
L3list = fin.readline()

but since I don't know how many lines I will have, is there another way to create individual lists?

like image 718
John Avatar asked Aug 26 '13 16:08

John


People also ask

How do I put all the lines of a text file into a list in Python?

Using file.The readlines() is a built-in Python method that returns a list containing each line in the file as a list element. The readlines() function returns all the lines in the file as a list where each line is an item in the list object.

How do I read a text file line by line in Python?

Method 1: Read a File Line by Line using readlines() readlines() is used to read all the lines at a single go and then return them as each line a string element in a list. This function can be used for small files, as it reads the whole file content to the memory, then split it into separate lines.


1 Answers

Do not create separate lists; create a list of lists:

results = []
with open('inputfile.txt') as inputfile:
    for line in inputfile:
        results.append(line.strip().split(','))

or better still, use the csv module:

import csv

results = []
with open('inputfile.txt', newline='') as inputfile:
    for row in csv.reader(inputfile):
        results.append(row)

Lists or dictionaries are far superiour structures to keep track of an arbitrary number of things read from a file.

Note that either loop also lets you address the rows of data individually without having to read all the contents of the file into memory either; instead of using results.append() just process that line right there.

Just for completeness sake, here's the one-liner compact version to read in a CSV file into a list in one go:

import csv

with open('inputfile.txt', newline='') as inputfile:
    results = list(csv.reader(inputfile))
like image 99
Martijn Pieters Avatar answered Nov 01 '22 17:11

Martijn Pieters