我正试图删除文本文件中的一行(10884121),它大约有3000万行长。这是我第一次尝试的方法,但是,当我执行它时,它运行了大约20秒,然后给我一个“内存错误”。有更好的方法吗?谢谢!在
import fileinput
import sys
f_in = 'C:\\Users\\Lucas\\Documents\\Python\\Pagelinks\\fullyCleaned2.txt'
f_out = 'C:\\Users\\Lucas\\Documents\\Python\\Pagelinks\\fullyCleaned3.txt'
with open(f_in, 'r') as fin:
with open(f_out, 'w') as fout:
linenums = [10884121]
s = [y for x, y in enumerate(fin) if x not in [line - 1 for line in linenums]]
fin.seek(0)
fin.write(''.join(s))
fin.truncate(fin.tell())
请尝试使用:
由于您试图将文件存储到列表中,内存不足的可能性很高。 请尝试以下操作:
这里我们逐行读取文件,并排除不需要的行,这可能不会耗尽内存。 您也可以尝试使用缓冲读取文件。 希望这有帮助。在
首先,您没有使用导入;您试图写入输入文件,而您的代码将整个文件读入内存。在
像这样的东西也许能让你省去很多麻烦-我们逐行阅读, 使用
enumerate
来计算行号;对于每一行,如果其编号是而不是被忽略的行列表中,我们将其写入输出:相关问题 更多 >
编程相关推荐