Python删除一个特定的行号

2024-10-03 00:32:04 发布

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

我正试图删除文本文件中的一行(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())

Tags: 方法inimporttxtforaswithopen
3条回答

请尝试使用:

import fileinput

f_in = 'C:\\Users\\Lucas\\Documents\\Python\\Pagelinks\\fullyCleaned2.txt'
f_out = 'C:\\Users\\Lucas\\Documents\\Python\\Pagelinks\\fullyCleaned3.txt'

f = open(f_out,'w')

counter=0

for line in fileinput.input([f_in]):
    counter=counter+1
    if counter != 10884121:
          f.write(line) # python will convert \n to os.linesep, maybe you need to add a os.linesep, check

f.close() # you can omit in most cases as the destructor will call it

由于您试图将文件存储到列表中,内存不足的可能性很高。 请尝试以下操作:

import fileinput
import sys

f_in = 'C:\\Users\\Lucas\\Documents\\Python\\Pagelinks\\fullyCleaned2.txt'
f_out = 'C:\\Users\\Lucas\\Documents\\Python\\Pagelinks\\fullyCleaned3.txt'
_fileOne = open(f_in,'r')
_fileTwo = open(f_out,'w')
linenums = set([10884121])
for lineNumber, line in enumerate(_fileOne):
    if lineNumber not in linenums:
        _fileTwo.writeLine(line)
_fileOne.close()
_fileTwo.close()

这里我们逐行读取文件,并排除不需要的行,这可能不会耗尽内存。 您也可以尝试使用缓冲读取文件。 希望这有帮助。在

首先,您没有使用导入;您试图写入输入文件,而您的代码将整个文件读入内存。在

像这样的东西也许能让你省去很多麻烦-我们逐行阅读, 使用enumerate来计算行号;对于每一行,如果其编号是而不是被忽略的行列表中,我们将其写入输出:

f_in = 'C:\\Users\\Lucas\\Documents\\Python\\Pagelinks\\fullyCleaned2.txt'
f_out = 'C:\\Users\\Lucas\\Documents\\Python\\Pagelinks\\fullyCleaned3.txt'

ignored_lines = [10884121]
with open(f_in, 'r') as fin, open(f_out, 'w') as fout:
    for lineno, line in enumerate(fin, 1):
        if lineno not in ignored_lines:
            fout.write(line)

相关问题 更多 >