<tutorialjinni.com/>

Python Read File Line by Line

Posted Under: Programming, Python, Tutorials on Nov 5, 2024
Reading a file line by line is a common task in Python, especially when dealing with large files or when you want to process each line individually. Python offers several methods for reading files line by line, each with specific use cases and advantages.

Basic File Reading Line by Line

The simplest way to read a file line by line is to use a for loop with a file object. This approach is memory-efficient and doesn’t load the entire file into memory, making it ideal for large files.
# Open the file in read mode
with open("PATH_TO_FILE", "r") as file:
    # Loop through each line in the file
    for line in file:
        # Print the line (including the newline character)
        print(line)

Python Read File Line by Line into a List

If you want to store each line as a separate item in a list, you can read the file line by line and append each line to a list.
# Initialize an empty list
lines_list = []

# Open the file in read mode
with open("PATH_TO_FILE", "r") as file:
    for line in file:
        # Append each line to the list
        lines_list.append(line.strip())  # .strip() removes the newline character

# Print the list
print(lines_list)

Using readlines() Without Newline Characters

The readlines() method reads all lines in a file and returns them as a list. However, by default, each line will include a newline character. To remove the newline, you can use list comprehension along with .strip().
# Open the file and use readlines() to get a list of lines
with open("PATH_TO_FILE", "r") as file:
    # Use list comprehension to remove newlines
    lines = [line.strip() for line in file.readlines()]

# Print the list
print(lines)

Python Read File Line by Line into an Array

In Python, the array module provides an array-like data structure for storing elements of a single type, typically numbers. If you need to store lines of text, lists are generally more suitable. See above Python Read File Line by Line into a List


imgae