Python3.7连接字符串并将其写入磁盘的快速方法

2024-07-05 10:10:38 发布

您现在位置:Python中文网/ 问答频道 /正文

是否有更好的实施方案:

file = open("./myFile.txt","w+")
for doc in allDocuments: #around 35 million documents
    file.write(str(doc.number)+"\r\n")
f.close()

目前,此实现每个文件需要20秒


Tags: intxtnumberfordocopenmyfiledocuments
2条回答

您可以缓冲输出并在块中写入:

with open("./myFile.txt", "w") as output:
    lines = []
    for doc in allDocuments:
        lines.append(f"{doc.number}\r\n")
        if len(lines) > 1000:
            output.writelines(lines)
            lines = []
    output.writelines(lines)

I/O不是真正的问题,您也不能对此做任何有用的事情:文件对象和操作系统都将执行某种形式的缓冲。您可以做的事情是您进行的方法调用的数量

with open("./myFile.txt", "w", newline='\r\n') as f:
    f.writelines(f'{doc.number}\n' for doc in allDocuments)

writelines方法接受一组字符串写入文件。(虽然documentation表示“list”,但它似乎指的是list,而不是list;生成器表达式似乎也可以工作。)生成器表达式根据需要生成writelines的每一行


这里有一个测试:

import random

def allDocuments():
    for i in range(35_000_000):
        yield random.randint(0, 100)

with open("tmp.txt", "w", newline='\r\n') as f:
    f.writelines(f'{doc}\n' for doc in allDocuments())

它在75秒内完成(大部分是由于对random.randint的重复调用),使用的内存不到6MB。(用常量值替换对random.randint的调用会将运行时间降低到30秒以下。)

相关问题 更多 >