Read a file line by line in Python
Last Updated : 21 May, 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 with open('filename.txt', 'r') as file: for line in file: print(line.strip())
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"] file1 = open('myfile.txt', 'w') file1.writelines(L) file1.close() file1 = open('myfile.txt', 'r') count = 0 print("Using for loop") for line in file1: count += 1 print("Line{}: {}".format(count, line.strip())) file1.close()
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.
Python with open('myfile.txt') as f: l = [line for line in f] print(l) with open('myfile.txt') as f: l = [line.rstrip() for line in f] print(l)
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.
Python L = ["Geeks\n", "for\n", "Geeks\n"] file1 = open('myfile.txt', 'w') file1.writelines(L) file1.close() file1 = open('myfile.txt', 'r') Lines = file1.readlines() count = 0 for line in Lines: count += 1 print("Line{}: {}".format(count, line.strip()))
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.
Python L = ["Geeks\n", "for\n", "Geeks\n"] with open("myfile.txt", "w") as fp: fp.writelines(L) count = 0 print("Using readlines()") with open("myfile.txt") as fp: l = fp.readlines() for line in l: count += 1 print("Line{}: {}".format(count, line.strip())) 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())) 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
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