Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a file line-by-line into a list?

How do I read every line of a file in Python and store each line as an element in a list?

I want to read the file line by line and append each line to the end of the list.

like image 967
Julie Raswick Avatar asked Jul 18 '10 22:07

Julie Raswick


People also ask

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.

How do I read a text file into a list?

You can read a text file using the open() and readlines() methods. To read a text file into a list, use the split() method. This method splits strings into a list at a certain character.


1 Answers

This code will read the entire file into memory:

with open(filename) as file:     lines = file.readlines() 

If you want to remove all whitespace characters (newlines and spaces) from the end of each line, use this instead:

with open(filename) as file:     lines = [line.rstrip() for line in file] 

(This avoids allocating an extra list from file.readlines().)

If you're working with a large file, then you should instead read and process it line-by-line:

with open(filename) as file:     for line in file:         print(line.rstrip()) 

In Python 3.8 and up you can use a while loop with the walrus operator like so:

with open(filename) as file:     while line := file.readline():         print(line.rstrip()) 
like image 139
SilentGhost Avatar answered Sep 23 '22 18:09

SilentGhost