python - 在Python中读取大文本文件

标签 python python-3.x file

我想从 Python 的文本文件中获取每一行(大约 10 亿行),并且从每一行中获取一些单词并插入到另一个文件中 我用过

with open('') as f:
   for line in f:
       process_line(line)

这个过程需要很多时间,我怎样才能在大约2小时内读完所有内容?

最佳答案

脚本性能的瓶颈可能来自于它同时写入 3 个文件,导致文件之间产生大量碎片,从而产生大量开销。

因此,在将 300 万个字写入输出文件之前,您可以缓冲一百万行(这应该占用不到 1GB 的内存),而不是在读取行时同时写入 3 个文件一次一个文件,这样会产生更少的文件碎片:

def write_words(words, *files):
    for i, file in enumerate(files):
        for word in words:
            file.write(word[i] + '\n')

words = []
with open('input.txt', 'r') as f, open('words1.txt', 'w') as out1, open('words2.txt', 'w') as out2, open('words3.txt', 'w') as out3:
    for count, line in enumerate(f, 1):
        words.append(line.rstrip().split(','))
        if count % 1000000 == 0:
            write_words(words, out1, out2, out3)
            words = []
    write_words(words, out1, out2, out3)

关于python - 在Python中读取大文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53087865/

相关文章:

python - 谷歌应用程序引擎上的 float 列表

python - 替换 Python 上的一行

python - Python 中的矩阵补全

python - 加强数据提取

python - 如何获取 pandas 中已选定行的索引?

6位毫秒的python datetime

python-3.x - 修改全局变量的NameError

python-3.x - Spark DataFrame 限制功能需要太多时间才能显示

c - 写入文件时,fputs() 不会更改行

C - 将用户输入存储在动态字符数组中?