How to read large files using Python
This article mainly introduces the method of using Python to read large files. Friends who need it can refer to it
Background
Recently When processing a text document (the file is about 2GB in size), a memoryError error occurred and the file reading was too slow. Later, I found two faster Large File Reading methods. This article will introduce these two reading methods.
Preparation
When we talk about "text processing", we usually mean the content of the processing. Python makes it very easy to read the contents of a text file into a string variable that can be manipulated. File objects provide three "read" methods: .read(), .readline(), and .readlines(). Each method can accept a variable to limit the amount of data read each time, but they generally do not use variables. .read() reads the entire file at a time, it is usually used to put the file contents into a string variable. However, .read() generates the most direct string representation of the file's contents, but it is unnecessary for continuous line-oriented processing, and such processing is not possible if the file is larger than available memory. The following is an example of the read() method:
try: f = open('/path/to/file', 'r') print f.read() finally: if f: f.close()
Calling read() will read the entire contents of the file at once. If the file is 10G, the memory will be exhausted. , so to be on the safe side, you can call the read(size) method repeatedly and read up to size bytes each time. In addition, calling readline() can read one line of content at a time, and calling readlines() can read all the content at once and return the list by line. Therefore, you need to decide how to call it according to your needs.
If the file is small, read() is the most convenient way to read it all at once; if the file size cannot be determined, it is safer to call read(size)
repeatedly; if it is a configuration file, It is most convenient to call readlines():
for line in f.readlines(): process(line) #
Read in chunks
It is easy to think of processing large files by dividing the large file into several small files for processing, and releasing this part of the memory after processing each small file. Iter and yield are used here:
def read_in_chunks(filePath, chunk_size=1024*1024): """ Lazy function (generator) to read a file piece by piece. Default chunk size: 1M You can set your own chunk size """ file_object = open(filePath) while True: chunk_data = file_object.read(chunk_size) if not chunk_data: break yield chunk_data if __name__ == "__main__": filePath = './path/filename' for chunk in read_in_chunks(filePath): process(chunk) # <do something with chunk>
Use With open()
with statements to open and close files, including throwing an inner block exception. for line in f file object f is treated as an iterator and automatically uses buffered IO and memory management, so you don't have to worry about large files.
The code is as follows:
#If the file is line based with open(...) as f: for line in f: process(line) # <do something with line>
##Optimization
Facing hundreds There is no problem using with open for large data with thousands of rows, but the different parameters will also lead to different efficiencies. After testing, the efficiency when the first parameter is "rb" is 6 times that of "r". It can be seen that binary reading is still the fastest mode.with open(filename,"rb") as f: for fLine in f: pass
Conclusion
Detailed explanation of how python reads text data and converts it into DataFrame format
The above is the detailed content of How to read large files using Python. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.
