Reading a File Line-by-Line into a List in Python
Storing each line of a file as an element in a list is a common task in Python. To achieve this, you can use the open() function with a loop that iterates through each line of the file.
Method:
To read a file line-by-line and append each line to a list, follow these steps:
Code:
with open(filename, 'r') as file: lines = [line.rstrip() for line in file]
Alternatively:
If you prefer to iterate over the file object directly and print each line, you can use the following code:
with open(filename, 'r') as file: for line in file: print(line.rstrip())
Python 3.8 and Later:
In Python 3.8 and later, you can use the walrus operator ('=') to streamline the code:
with open(filename, 'r') as file: while line := file.readline(): print(line.rstrip())
Additional Notes:
with open(filename, 'r', encoding='UTF-8') as file:
The above is the detailed content of How Can I Read a File Line by Line into a List in Python?. For more information, please follow other related articles on the PHP Chinese website!