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.
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.
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.
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With