Read a file line by line in Python
Last Updated :
02 Jan, 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
Python
# Open the file in read mode
with open('filename.txt', 'r') as file:
# Read each line in the file
for line in file:
# Print each line
print(line.strip())
Read a File Line by Line 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.
Python
L = ["Geeks\n", "for\n", "Geeks\n"]
# Writing to file
file1 = open('myfile.txt', 'w')
file1.writelines(L)
file1.close()
# Opening file
file1 = open('myfile.txt', 'r')
count = 0
# Using for loop
print("Using for loop")
for line in file1:
count += 1
print("Line{}: {}".format(count, line.strip()))
# Closing files
file1.close()
Output:
Using for loop
Line1: Geeks
Line2: for
Line3: Geeks
Read a File Line by Line 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.
Python
with open('myfile.txt') as f:
lines = [line for line in f]
print(lines)
# removing the new line characters
with open('myfile.txt') as f:
lines = [line.rstrip() for line in f]
print(lines)
Output:
['Geeks\n', 'For\n', 'Geeks']
['Geeks', 'For', 'Geeks']
Read a File Line by Line 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.
Python
L = ["Geeks\n", "for\n", "Geeks\n"]
# writing to file
file1 = open('myfile.txt', 'w')
file1.writelines(L)
file1.close()
# Using readlines()
file1 = open('myfile.txt', 'r')
Lines = file1.readlines()
count = 0
# Strips the newline character
for line in Lines:
count += 1
print("Line{}: {}".format(count, line.strip()))
Output:
Line1: Geeks
Line2: for
Line3: Geeks
Python With Statement
Using Python With statement, the file must be explicitly closed, and forgetting to do so can cause bugs, as changes may not take effect. To prevent this, the with
statement can be used. It simplifies resource management like file streams, ensuring proper handling and making the code cleaner by automatically closing the file, without needing file.close()
.
Python
L = ["Geeks\n", "for\n", "Geeks\n"]
# Writing to file
with open("myfile.txt", "w") as fp:
fp.writelines(L)
# using readlines()
count = 0
print("Using readlines()")
with open("myfile.txt") as fp:
Lines = fp.readlines()
for line in Lines:
count += 1
print("Line{}: {}".format(count, line.strip()))
# Using readline()
count = 0
print("\nUsing readline()")
with open("myfile.txt") as fp:
while True:
count += 1
line = fp.readline()
if not line:
break
print("Line{}: {}".format(count, line.strip()))
# Using for loop
count = 0
print("\nUsing for loop")
with open("myfile.txt") as fp:
for line in fp:
count += 1
print("Line{}: {}".format(count, line.strip()))
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
Similar Reads
Read a file without newlines in Python
When working with files in Python, it's common to encounter scenarios where you need to read the file content without including newline characters. Newlines can sometimes interfere with the processing or formatting of the data. In this article, we'll explore different approaches to reading a file wi
2 min read
Compare two Files line by line in Python
In Python, there are many methods available to this comparison. In this Article, We'll find out how to Compare two different files line by line. Python supports many modules to do so and here we will discuss approaches using its various modules. This article uses two sample files for implementation.
3 min read
fileinput.lineno() in Python
With the help of fileinput.lineno() method, we can get the line number for every line on line read from input file by using fileinput.lineno() method. Syntax : fileinput.lineno() Return : Return the line number. Example #1 : In this example we can see that by using fileinput.lineno() method, we are
1 min read
How to Read from a File in Python
Reading from a file in Python means accessing and retrieving the contents of a file, whether it be text, binary data or a specific data format like CSV or JSON. Python provides built-in functions and methods for reading a file in python efficiently.Example File: geeks.txtHello World Hello GeeksforGe
5 min read
Open a File in Python
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). Text files: In this type of file, each line of text is terminated with a special character called EOL
6 min read
Reading binary files in Python
Reading binary files means reading data that is stored in a binary format, which is not human-readable. Unlike text files, which store data as readable characters, binary files store data as raw bytes. Binary files store data as a sequence of bytes. Each byte can represent a wide range of values, fr
5 min read
Count number of lines in a text file in Python
Counting the number of characters is important because almost all the text boxes that rely on user input have a certain limit on the number of characters that can be inserted. For example, If the file is small, you can use readlines() or a loop approach in Python. Input: line 1 line 2 line 3 Output:
3 min read
Read a CSV into list of lists in Python
In this article, we are going to see how to read CSV files into a list of lists in Python. Method 1: Using CSV moduleWe can read the CSV files into different data structures like a list, a list of tuples, or a list of dictionaries.We can use other modules like pandas which are mostly used in ML appl
2 min read
How to read numbers in CSV files in Python?
Prerequisites: Reading and Writing data in CSV, Creating CSV files CSV is a Comma-Separated Values file, which allows plain-text data to be saved in a tabular format. These files are stored in our system with a .csv extension. CSV files differ from other spreadsheet file types (like Microsoft Excel
4 min read
Read File As String in Python
Python provides several ways to read the contents of a file as a string, allowing developers to handle text data with ease. In this article, we will explore four different approaches to achieve this task. Each approach has its advantages and uses cases, so let's delve into them one by one. Read File
3 min read