Read a file line by line in Python

In Python, you can read a file line by line using a for loop, the readline() method, or the readlines() method. Here are three common ways to do it:

This is the most efficient way to read a file line by line because it doesn't load the entire file into memory at once.

# Open the file in read mode
with open("your_file.txt", "r") as file:
    for line in file:
        # Process each line
        print(line.strip())  # .strip() removes trailing newline characters

2. Using readline() Method

The readline() method reads one line at a time. You can use it with a while loop to keep reading until the end of the file.

with open("your_file.txt", "r") as file:
    line = file.readline()
    while line:
        print(line.strip())
        line = file.readline()  # Read the next line

3. Using readlines() Method

The readlines() method reads all lines in the file and returns them as a list. This can be memory-intensive for large files, so it's best used for smaller files.

with open("your_file.txt", "r") as file:
    lines = file.readlines()
    for line in lines:
        print(line.strip())

Notes

  • Always use with open(...) as it ensures the file is properly closed after reading.
  • The strip() method is helpful to remove any trailing newline characters (\n).

댓글

이 블로그의 인기 게시물

To switch to a specific tag in a Git repository

How to checkout branch of remote git, 깃 리모트 브랜치 체크아웃

Using the MinIO API via curl

To download a file from MinIO using Spring Boot, 스프링부트 Minio 사용하기

리눅스의 부팅과정 (프로세스, 서비스 관리)

Chromium 개발 환경 세팅, 크로미움 개발 준비하기

Joining an additional control plane node to an existing Kubernetes cluster

urllib3 with proxy settings

CDPEvents in puppeteer

Avro + Grpc in python