The Wayback Machine - https://web.archive.org/web/20240913104425/https://www.geeksforgeeks.org/read-a-file-line-by-line-in-python/
Open In App

Read a file line by line in Python

Last Updated : 28 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisites:

Python provides inbuilt functions for creating, writing, and reading files. There are two types of files that 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.

Learning Efficient file handling techniques are vital for effective data manipulation and analysis in Python. If you wish to explore the full potential of Python’s file handling capabilities check out our Complete Machine Learning & Data Science Program . Learn how to efficiently read, write, and manipulate files, enabling you to tackle complex data challenges and advance your career in programming and data science. Enroll now to take your Python skills to the next level!

Method 1: Read a File Line by Line using readlines()

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.

Example:

Python
# Python code to
# demonstrate readlines()

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

The time complexity of the given Python code is O(n), where n is the total number of lines in the file

The auxiliary space complexity of the code is O(n), where n is the total number of lines in the file.

Method 2: Read a File Line by Line using readline()

readline() function reads a line of the file and return it in the form of the string. It takes a parameter n, which specifies the maximum number of bytes that will be read. However, does not reads more than one line, even if n exceeds the length of the line. It will be efficient when reading a large file because instead of fetching all the data in one go, it fetches line by line. readline() returns the next line of the file which contains a newline character in the end. Also, if the end of the file is reached, it will return an empty string.

Example:

STEP BY STEP APPROACH :

  1. Create a list L with three string elements containing newline characters.
  2. Open a file named myfile.txt in write mode and assign it to the variable file1.
  3. Write the contents of the list L to the file using the writelines() method of the file object file1.
  4. Close the file object file1 using the close() method.
  5. Open the file named myfile.txt in read mode and assign it to the variable file1.
  6. Initialize a variable count to 0.
  7. Start an infinite loop.
  8. Increment the variable count by 1 in each iteration of the loop.
  9. Read the next line from the file object file1 using the readline() method and assign it to the variable line.
  10. Check if the line variable is empty. If it is empty, it means that the end of the file has been reached. In that case, break out of the loop using the break statement.
  11. Print the value of count and the contents of line using the format() method of the string class. The strip() method is used to remove the newline character at the end of the line.
  12. Close the file object file1 using the close() method.
Python
# Python program to
# demonstrate readline()

L = ["Geeks\n", "for\n", "Geeks\n"]

# Writing to a file
file1 = open('myfile.txt', 'w')
file1.writelines((L))
file1.close()

# Using readline()
file1 = open('myfile.txt', 'r')
count = 0

while True:
    count += 1

    # Get next line from file
    line = file1.readline()

    # if line is empty
    # end of file is reached
    if not line:
        break
    print("Line{}: {}".format(count, line.strip()))

file1.close()

Output:

Line1 Geeks
Line2 for
Line3 Geeks

Method 3: Read a File Line by Line using for 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 for 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 a combination with using the iterable object. This approach takes fewer lines of code, which is always the best practice worthy of following.

Example:

Python
# Python program to
# demonstrate reading files
# using for loop

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

Method 4: Read a File Line by Line using for loop and 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.

Example

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']

With statement

In the above approaches, every time the file is opened it is needed to be closed explicitly. If one forgets to close the file, it may introduce several bugs in the code, i.e. many changes in files do not go into effect until the file is properly closed. To prevent this with statement can be used. The With statement in Python is used in exception handling to make the code cleaner and much more readable. It simplifies the management of common resources like file streams. Observe the following code example on how the use of with statement makes the code cleaner. There is no need to call file.close() when using with the statement. The with the statement itself ensures proper acquisition and release of resources.

Example:

Python
# Python program to
# demonstrate with
# statement

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

Read a file line by line in Python – FAQs

How to read lines in a file in Python?

Read all lines into a list using readlines()

with open('file.txt', 'r') as file:
lines = file.readlines()

How to read file line by line using while in Python?

Iterate through each line using readline() and a while loop

with open('file.txt', 'r') as file:
line = file.readline()
while line:
print(line.strip())
line = file.readline()

How to read file line by line using while in Python?

Read specific lines using islice from itertools

from itertools import islice
with open('file.txt', 'r') as file:
for line in islice(file, start_line, end_line):
print(line.strip())

What does readline() do in Python?

Read a single line using readline()

with open('file.txt', 'r') as file:
line = file.readline()
print(line)

How to read a specific portion of a file in Python?

Move to a specific position with seek() and read data

with open('file.txt', 'r') as file:
file.seek(start_position)
data = file.read(num_bytes)
print(data)


Similar Reads

Read content from one file and write it into another file
Prerequisite: Reading and Writing to text files in Python Python provides inbuilt 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 call
2 min read
Read a Particular Page from a PDF File in Python
Document processing is one of the most common use cases for the Python programming language. This allows the language to process many files, such as database files, multimedia files and encrypted files, to name a few. This article will teach you how to read a particular page from a PDF (Portable Document Format) file in Python. Method 1: Using Pymu
4 min read
How to read from a file in Python
Python provides inbuilt functions for creating, writing and reading files. There are two types of files that 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 (End of Line), which is the new line
5 min read
Upload file and read its content in cherrypy python
CherryPy is a web framework of Python which provides a friendly interface to the HTTP protocol for Python developers. It is also called a web application library. It allows developers to build web applications in much the same way they would build any other object-oriented Python program. This results in smaller source code developed in less time.
3 min read
Read List of Dictionaries from File in Python
A dictionary in Python is a collection where every value is mapped to a key. Since they are unordered and there is no constraint on the data type of values and keys stored in the dictionary, it is tricky to read dictionaries from files in Python. Read a List of Dictionary from Text Files in PythonUsing Pickle ModuleUsing read( ) MethodThe problem s
3 min read
How to read Dictionary from File in Python?
A Dictionary in Python is collection of key-value pairs, where key is always unique and oftenly we need to store a dictionary and read it back again. We can read a dictionary from a file in 3 ways: Using the json.loads() method : Converts the string of valid dictionary into json form. Using the ast.literal_eval() method : Function safer than the ev
2 min read
Read Properties File Using jproperties in Python
In this article, we are going to see how to read properties file in python using jproperties module. It is a Java Property file parser and writer for Python. For installation run this command into your terminal. pip install jproperties Various properties of this module: get() Method or Index-Based access to reading the values associated with the ke
2 min read
How to read a numerical data or file in Python with numpy?
Prerequisites: Numpy NumPy is a general-purpose array-processing package. It provides a high-performance multidimensional array object and tools for working with these arrays. This article depicts how numeric data can be read from a file using Numpy. Numerical data can be present in different formats of file : The data can be saved in a txt file wh
4 min read
Python - Read file from sibling directory
In this article, we will discuss the method to read files from the sibling directory in Python. First, create two folders in a root folder, and one folder will contain the python file and the other will contain the file which is to be read. Below is the dictionary tree: Directory Tree: root : | |__Sibling_1: | \__demo.py | |__Sibling_2: | \__file.t
3 min read
How to Read Text File Into List in Python?
In this article, we are going to see how to read text files into lists in Python. File for demonstration: Example 1: Converting a text file into a list by splitting the text on the occurrence of '.'. We open the file in reading mode, then read all the text using the read() and store it into a variable called data. after that we replace the end of t
2 min read
Read a text file into a string variable and strip newlines in Python
It is quite a common requirement for users to remove certain characters from their text files while displaying. This is done to assure that only displayable characters are displayed or data should be displayed in a specific structure. This article will teach you how to read a text file into a string variable and strip newlines using Python. For dem
5 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 As String In PythonBelow are some of the approach
3 min read
Read CSV File without Unnamed Index Column in Python
Whenever the user creates the data frame in Pandas, the Unnamed index column is by default added to the data frame. The article aims to demonstrate how to read CSV File without Unnamed Index Column using index_col=0 while reading CSV. Read CSV File without Unnamed Index Column Using index_col=0 while reading CSVThe way of explicitly specifying whic
2 min read
How to read specific lines from a File in Python?
Text files are composed of plain text content. Text files are also known as flat files or plain files. Python provides easy support to read and access the content within the file. Text files are first opened and then the content is accessed from it in the order of lines. By default, the line numbers begin with the 0th index. There are various ways
3 min read
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 without newlines in Python. Read a file without newl
2 min read
Read JSON file using Python
The full form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-
4 min read
Read a zipped file as a Pandas DataFrame
In this article, we will try to find out how can we read data from a zip file using a panda data frame. Why we need a zip file? People use related groups of files together and to make files compact, so they are easier and faster to share via the web. Zip files are ideal for archiving since they save storage space. And, they are also useful for secu
2 min read
How to read a CSV file to a Dataframe with custom delimiter in Pandas?
Python is a good language for doing data analysis because of the amazing ecosystem of data-centric python packages. pandas package is one of them and makes importing and analyzing data so much easier.Here, we will discuss how to load a csv file into a Dataframe. It is done using a pandas.read_csv() method. We have to import pandas library to use th
3 min read
How to read csv file with Pandas without header?
Prerequisites: Pandas A header of the CSV file is an array of values assigned to each of the columns. It acts as a row header for the data. This article discusses how we can read a csv file without header using pandas. To do this header attribute should be set to None while reading the file. Syntax: read_csv("file name", header=None) ApproachImport
1 min read
Read Text file into PySpark Dataframe
In this article, we are going to see how to read text files in PySpark Dataframe. There are three ways to read text files into PySpark DataFrame. Using spark.read.text()Using spark.read.csv()Using spark.read.format().load() Using these we can read a single text file, multiple files, and all files from a directory into Spark DataFrame and Dataset. T
3 min read
PySpark - Read CSV file into DataFrame
In this article, we are going to see how to read CSV files into Dataframe. For this, we will use Pyspark and Python. Files Used: authorsbook_authorbooksRead CSV File into DataFrame Here we are going to read a single CSV into dataframe using spark.read.csv and then create dataframe with this data using .toPandas(). C/C++ Code from pyspark.sql import
2 min read
Read File Without Saving in Flask
Flask is a flexible, lightweight web-development framework built using python. A Flask application is a Python script that runs on a web server, which listens to HTTP requests and returns responses. It is designed for simple and faster development. In this article we will discuss how can we Read files without Saving them in Flask, we will also veri
2 min read
Upload and Read Excel File in Flask
In this article, we will look at how to read an Excel file in Flask. We will use the Python Pandas library to parse this excel data as HTML to make our job easier. Pandas additionally depend on openpyxl library to process Excel file formats. Before we begin, make sure that you have installed both Flask and Pandas libraries along with the openpyxl d
3 min read
Python - Read blob object in python using wand library
BLOB stands for Binary Large OBject. A blob is a data type that can store binary data. This is different than most other data types used in databases, such as integers, floating point numbers, characters, and strings, which store letters and numbers. BLOB is a large complex collection of binary data which is stored in Database. Basically BLOB is us
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. Files in use: file.txt file1.txt Method 1: Using
3 min read
Pulling a random word or string from a line in a text file in Python
File handling in Python is really simple and easy to implement. In order to pull a random word or string from a text file, we will first open the file in read mode and then use the methods in Python's random module to pick a random word. There are various ways to perform this operation: This is the text file we will read from: Method 1: Using rando
2 min read
Find line number of a specific string or substring or word from a .txt file in Python
Finding the line number of a specific string and its substring is a common operation performed by text editors or any application with some level of text processing capabilities. In this article, you will learn how to find line number of a specific string or substring or word from a .txt (plain text) file using Python. The problem in hand could be
4 min read
How to Find the Longest Line from a Text File in Python
Finding the longest line from a text file consists of comparing the lengths of each line to determine which one is the longest. This can be done efficiently using various methods in Python. In this article, we will explore three different approaches to Finding the Longest Line from a Text File in Python. Find the Longest Line from a Text File in Py
3 min read
Python - Get file id of windows file
File ID is a unique file identifier used on windows to identify a unique file on a Volume. File Id works similar in spirit to a inode number found in *nix Distributions. Such that a fileId could be used to uniquely identify a file in a volume. We would be using an command found in Windows Command Processor cmd.exe to find the fileid of a file. In o
3 min read
How to save file with file name from user using Python?
Prerequisites: File Handling in PythonReading and Writing to text files in Python Saving a file with the user's custom name can be achieved using python file handling concepts. Python provides inbuilt functions for working with files. The file can be saved with the user preferred name by creating a new file, renaming the existing file, making a cop
5 min read
Article Tags :
Practice Tags :