处理大文件时,可以采用以下方法来避免内存溢出问题:
with open('filename.txt', 'r') as file:
for line in file:
# 处理每一行的数据
with open('filename.txt', 'r') as file:
chunk_size = 1024 # 设置每次读取的块大小
while True:
data = file.read(chunk_size)
if not data:
break
# 处理当前块的数据
def read_file(filename):
with open(filename, 'r') as file:
for line in file:
yield line
for data in read_file('filename.txt'):
# 处理每一行的数据
import pandas as pd
chunk_size = 1000 # 设置每次读取的块大小
for chunk in pd.read_csv('filename.csv', chunksize=chunk_size):
# 处理当前块的数据
通过以上方法,可以有效地处理大文件并避免内存溢出问题。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: Python数据存储在实时性方面表现如何