在Python中读取较大文件的最有效方法是什么?

问题描述 投票:0回答:1

我必须写一些东西来打开包含 1000 个非空单词的“signals.txt”文件,每 40 个单词取第 10 个字母,并将这些字母写入文件“结果”(字母正在生成另一个单词)。我想以最小的内存使用量来做到这一点,所以我用 3 种不同的方式做到了这一点,并使用了 tracemalloc 模块来监视内存使用情况。

关键是我真的不知道如何读取tracemalloc.take_snapshot 的输出。 我认为方式1是最有效的,基于tracemalloc,但我不知道我是否正确使用它。

那么谁能告诉我哪种方式最有效? 或者也许这 3 种方式正在做同样的事情。 有没有更好的办法呢?

是的,我知道当我只有 1000 行长的 txt 文件时,“方式 2”可能是最好的,但我们假设该文件比这个大得多。

我的代码

import tracemalloc
tracemalloc.start()


#------------------------Way 1----------------------

def Gen():
    with open('signals.txt','rt') as file:
        text = file.read().splitlines()
        for i in range(39,len(text),40):
            yield text[i][9]


with open('results.txt','w') as results:
    for i in Gen():
        results.write(i)


#------------------------Way 2----------------------

 with open('signals.txt','rt') as file:
     with open('results.txt','w') as results:
         text = file.read().splitlines()
         results.write(''.join(text[i][9] for i in range(39,len(text),40)))


#------------------------Way 3----------------------
#here I tried to do this without making list with file content

 with open('signals.txt','rt') as file:
     with open('results.txt','w') as results:
         iWord=39
         for index,word in enumerate(file):
             if index == iWord:
                 results.write(word[9])
                 iWord+=40


snapshot = tracemalloc.take_snapshot()

for stat in snapshot.statistics('lineno'):
    print(stat)

tracemalloc.stop()
python performance file memory-efficient
1个回答
1
投票

file.read()
读取整个文件。 您最好使用
file.readline()
从文件中读取下一行。

迭代文本文件也可以实现

readline()
。所以第三种方法一定是最有效的。

阅读详细文档

© www.soinside.com 2019 - 2024. All rights reserved.