Home > Backend Development > Python Tutorial > How Can I Read a File Line by Line into a List in Python?

How Can I Read a File Line by Line into a List in Python?

DDD
Release: 2024-12-31 05:45:17
Original
681 people have browsed it

How Can I Read a File Line by Line into a List in Python?

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:

  1. Use the open() function to open the file and specify the read mode ('r').
  2. Loop through the file object using a for loop.
  3. In each iteration, use the rstrip() method to remove any trailing whitespace characters from the current line.
  4. Append the cleaned line to the list.

Code:

with open(filename, 'r') as file:
    lines = [line.rstrip() for line in file]
Copy after login

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())
Copy after login

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())
Copy after login

Additional Notes:

  • The with block automatically handles file opening and closing.
  • If you need to specify the access mode and character encoding, you can modify the open() call as follows:
with open(filename, 'r', encoding='UTF-8') as file:
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template