VOOZH about

URL: https://www.geeksforgeeks.org/python/read-a-file-line-by-line-in-python/

⇱ Read a file line by line in Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Read a file line by line in Python

Last Updated : 12 Jul, 2025

Python provides built-in functions for creating, writing, and reading files. Two types of files can be handled in Python, normal text files and binary files (written in binary language, 0s, and 1s). In this article, we are going to study reading line by line from a file.

Example:

Using Loop

An iterable object is returned by open() function while opening a file. This final way of reading a file line-by-line includes iterating over a file object in a loop. In doing this we are taking advantage of a built-in Python function that allows us to iterate over the file object implicitly using a for loop in combination with using the iterable object.

Output

Using for loop
Line1: Geeks
Line2: for
Line3: Geeks

Using List Comprehension

A list comprehension consists of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element. Here, we will read the text file and print the raw data including the new line character in another output we removed all the new line characters from the list.

Output:

['Geeks\n', 'For\n', 'Geeks']
['Geeks', 'For', 'Geeks']

Using readlines()

Python 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. We can iterate over the list and strip the newline '\n' character using strip() function.

Output

Line1: Geeks
Line2: for
Line3: Geeks

Python With Statement

When working with files in Python, it is important to close the file after operations to avoid bugs such as unsaved changes or resource leaks. Normally, you would need to explicitly call file.close() after opening a file.

However, using the with statement simplifies this process. It automatically handles opening and closing the file for you, ensuring the file is properly closed as soon as the code block inside the with statement finishes execution even if an error occurs. This eliminates the need to manually close the file and results in cleaner, safer code.

Output

Using readlines()
Line1: Geeks
Line2: for
Line3: Geeks

Using readline()
Line1: Geeks
Line2: for
Line3: Geeks

Using for loop
Line1: Geeks
Line2: for
Line3: Geeks
Comment
Article Tags: