[python] 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?

This question is related to python list python-3.x file-io

The answer is


with open('path/to/file') as infile: # try open('...', 'rb') as well
    answer = [line.strip().split(',') for line in infile]

If you want the numbers as ints:

with open('path/to/file') as infile:
    answer = [[int(i) for i in line.strip().split(',')] for line in infile]

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))

Create a list of lists:

with open("/path/to/file") as file:
    lines = []
    for line in file:
        # The rstrip method gets rid of the "\n" at the end of each line
        lines.append(line.rstrip().split(","))

lines=[]
with open('file') as file:
   lines.append(file.readline())

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>

Examples related to python-3.x

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation Replace specific text with a redacted version using Python Upgrade to python 3.8 using conda "Permission Denied" trying to run Python on Windows 10 Python: 'ModuleNotFoundError' when trying to import module from imported package What is the meaning of "Failed building wheel for X" in pip install? How to downgrade python from 3.7 to 3.6 I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? Iterating over arrays in Python 3 How to upgrade Python version to 3.7?

Examples related to file-io

Python, Pandas : write content of DataFrame into text File Saving response from Requests to file How to while loop until the end of a file in Python without checking for empty line? Getting "java.nio.file.AccessDeniedException" when trying to write to a folder How do I add a resources folder to my Java project in Eclipse Read and write a String from text file Python Pandas: How to read only first n rows of CSV files in? Open files in 'rt' and 'wt' modes How to write to a file without overwriting current contents? Write objects into file with Node.js