How to read large text files in Python? - GeeksforGeeks (2024)

Last Updated : 13 Sep, 2022

Summarize

Comments

Improve

In this article, we will try to understand how to read a large text file using the fastest way, with less memory usage using Python.

To read large text files in Python, we can use the file object as an iterator to iterate over the file and perform the required task. Since the iterator just iterates over the entire file and does not require any additional data structure for data storage, the memory consumed is less comparatively. Also, the iterator does not perform expensive operations like appending hence it is time-efficient as well. Files are iterable in Python hence it is advisable to use iterators.

Problem with readline() method to read large text files

In Python, files are read by using the readlines() method. The readlines() method returns a list where each item of the list is a complete sentence in the file. This method is useful when the file size is small. Since readlines() method appends each line to the list and then returns the entire list it will be time-consuming if the file size is extremely large say in GB. Also, the list will consume a large chunk of the memory which can cause memory leakage if sufficient memory is unavailable.

Read large text files in Python using iterate

In this method, we will import fileinput module. The input() method of fileinput module can be used to read large files. This method takes a list of filenames and if no parameter is passed it accepts input from the stdin, and returns an iterator that returns individual lines from the text file being scanned.

Note: We will also use it to calculate the time taken to read the file using Python time.

Python3

# import module

import fileinput

import time

#time at the start of program is noted

start = time.time()

#keeps a track of number of lines in the file

count = 0

for lines in fileinput.input(['sample.txt']):

print(lines)

count = count + 1

#time at the end of program execution is noted

end = time.time()

#total time taken to print the file

print("Execution time in seconds: ",(end - start))

print("No. of lines printed: ",count)

Output:

How to read large text files in Python? - GeeksforGeeks (1)

The fastest way to read a large text file using the iterator of a file object

Here, the only difference is that we will use the iterator of a file object. The open() function wraps the entire file into a file object. After that, we use an iterator to get the lines in the file object. We open the file in a ‘with’ block as it automatically closes the file as soon as the entire block executes.

Python3

import time

start = time.time()

count = 0

with open("sample.txt") as file:

for line in file:

print(line)

count = count + 1

end = time.time()

print("Execution time in seconds: ",(end-start))

print("No of lines printed: ",count)

Output:

The time required in the second approach is comparatively less than the first method.

How to read large text files in Python? - GeeksforGeeks (2)



Please Login to comment...

How to read large text files in Python? - GeeksforGeeks (2024)
Top Articles
Binance.US Delists Amp Token That SEC Deemed a Security
Here’s How Often You Should Look at Your Budget - Atypical Finance
Tlc Africa Deaths 2021
Costco The Dalles Or
Lowes 385
Tanger Outlets Sevierville Directory Map
Cvs Devoted Catalog
Mndot Road Closures
Lesson 3 Homework Practice Measures Of Variation Answer Key
A.e.a.o.n.m.s
Zoebaby222
R Tiktoksweets
10 Great Things You Might Know Troy McClure From | Topless Robot
Theycallmemissblue
House Party 2023 Showtimes Near Marcus North Shore Cinema
Moonshiner Tyler Wood Net Worth
Craigslist Mt Pleasant Sc
Mikayla Campinos Laek: The Rising Star Of Social Media
Craigslist Southern Oregon Coast
Tu Pulga Online Utah
How many days until 12 December - Calendarr
Crossword Help - Find Missing Letters & Solve Clues
Meridian Owners Forum
The 15 Best Sites to Watch Movies for Free (Legally!)
Booknet.com Contract Marriage 2
Kroger Feed Login
The Eight of Cups Tarot Card Meaning - The Ultimate Guide
Coindraw App
The Powers Below Drop Rate
Jailfunds Send Message
Planned re-opening of Interchange welcomed - but questions still remain
United E Gift Card
Redbox Walmart Near Me
Petsmart Distribution Center Jobs
Go Upstate Mugshots Gaffney Sc
Facebook Marketplace Marrero La
Imperialism Flocabulary Quiz Answers
Aveda Caramel Toner Formula
Philadelphia Inquirer Obituaries This Week
Michael Jordan: A timeline of the NBA legend
Adam Bartley Net Worth
18 terrible things that happened on Friday the 13th
craigslist: modesto jobs, apartments, for sale, services, community, and events
Janaki Kalaganaledu Serial Today Episode Written Update
Noh Buddy
Hawkview Retreat Pa Cost
Dineren en overnachten in Boutique Hotel The Church in Arnhem - Priya Loves Food & Travel
Bismarck Mandan Mugshots
Freightliner Cascadia Clutch Replacement Cost
Craigslist Free Cats Near Me
Koniec veľkorysých plánov. Prestížna LEAF Academy mení adresu, masívny kampus nepostaví
Latest Posts
Article information

Author: Catherine Tremblay

Last Updated:

Views: 6380

Rating: 4.7 / 5 (67 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Catherine Tremblay

Birthday: 1999-09-23

Address: Suite 461 73643 Sherril Loaf, Dickinsonland, AZ 47941-2379

Phone: +2678139151039

Job: International Administration Supervisor

Hobby: Dowsing, Snowboarding, Rowing, Beekeeping, Calligraphy, Shooting, Air sports

Introduction: My name is Catherine Tremblay, I am a precious, perfect, tasty, enthusiastic, inexpensive, vast, kind person who loves writing and wants to share my knowledge and understanding with you.