深度阅读

How to iterate over a file in chunks in Python?

作者
作者
2023年08月22日
更新时间
8.76 分钟
阅读时间
0
阅读量

To iterate over a file in chunks in Python, you can use a combination of the with keyword, the open() function, and a loop that reads a fixed number of bytes from the file. Here is an example:

chunk_size = 1024 # size of each chunk in bytes
with open('myfile.txt', 'rb') as file:
    while True:
        data = file.read(chunk_size)
        if not data:
            break
        # process the current chunk of data
        print(data)

In this example, we open the file ‘myfile.txt’ in binary mode (‘rb’), and then use a while loop to read chunks of data from the file using the read() method. If there is no more data to read, the loop exits. Inside the loop, you can perform whatever processing is necessary on the current chunk of data.

Note that you can adjust the chunk_size variable to control the size of each chunk of data read from the file.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。