打开25GB文本文件进行处理

Dav*_*542 4 python performance

我有一个需要处理的25GB文件.这是我目前正在做的事情,但打开需要很长时间:

collection_pricing = os.path.join(pricing_directory, 'collection_price')
with open(collection_pricing, 'r') as f:
    collection_contents = f.readlines()

length_of_file = len(collection_contents)

for num, line in enumerate(collection_contents):
    print '%s / %s' % (num+1, length_of_file)
    cursor.execute(...)
Run Code Online (Sandbox Code Playgroud)

我怎么能改善这个?

nos*_*nos 7

  1. 除非文件中的行确实非常大,否则不要在每行打印进度.打印到终端非常慢.打印进度,例如每100行或每1000行.

  2. 使用可用的操作系统工具来获取文件的大小 - os.path.getsize()请参阅使用Python获取文件大小?

  3. 摆脱readlines()以避免将25GB读入内存.而是逐行读取和处理,参见例如如何在python中逐行读取大文件