gpt4 book ai didi

python - 打开一个 25GB 的文本文件进行处理

转载 作者:太空狗 更新时间:2023-10-30 01:54:23 24 4
gpt4 key购买 nike

我有一个 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(...)

我该如何改进?

最佳答案

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

  2. 使用可用的操作系统工具获取文件的大小 - os.path.getsize(),参见 Getting file size in Python?

  3. 去掉 readlines() 以避免将 25GB 读入内存。而是逐行阅读和处理,参见例如How to read large file, line by line in python

关于python - 打开一个 25GB 的文本文件进行处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25879262/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com