Python:从fi中删除某些行

2024-03-28 21:05:01 发布

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

我正在制作一个程序,从现有文件中删除某些行。它将file1作为条目(f1),它查找特定的模式,如果找到它,它将修改行(使其与另一个文件兼容),并将此修改保存在变量“mark”中。它打开另一个文件f2,并在其中搜索“mark”。如果它在f2中的某一行中找到“mark”,我必须删除该行和后面的三行。问题是,当我运行它时,程序会删除f2中的所有内容,因此得到一个空文件。你知道吗

new=''
pattern2 = '2:N:0:8'
i=0


f1=open('test_reverse.txt','r')
for line in f1:
    if pattern2 in line:
        mark=line.replace('2:N:0:8','1:N:0:8')
        f2=open('test_OKforward2.txt','r')
        lines=f2.readlines()
        for i, line in enumerate(lines):
            if mark in lines[i]:
                e=lines[i]
                e1=lines[i+1]
                e2=lines[i+2]
                e3=lines[i+3]
                new=e+e1+e2+e3
            f3=open('test_OKforward2.txt','w')
            if line!=new:
                f3.write(line)

我也尝试了next()函数,但得到了相同的结果和“stop iteration”错误。你知道吗


Tags: 文件intest程序txtnewforif
1条回答
网友
1楼 · 发布于 2024-03-28 21:05:01

The thing is that when I run it, the program deletes everything from f2, so I get an empty file as a result.

每当你打开一个文件进行写作时,里面的所有东西都会丢失。你必须重新写你想保留在文件中的所有东西,并排除你想删除的东西。你知道吗

请注意以下几行:

f2=open('test_OKforward2.txt','r')
# ...
f3=open('test_OKforward2.txt','w')

问题是f3正在打开与f2相同的文件,以便为文件f2行上的每个循环写入。你知道吗

基本上,在添加行之后,您将重新打开文件进行写入,从而消除以前的内容。你知道吗

首先:您应该从循环中删除f3=open,循环在f2的每一行上进行迭代(即在循环之外的其他位置执行此操作)。这是主要问题。你知道吗

第二步:使用临时文件代替进程,最后将临时文件重命名为原来的文件。你知道吗

第三:您没有关闭文件。考虑使用上下文管理器。您的代码看起来更像这样:

with open('something.txt') as f2:
    # do something with f2;
    # f2 with be automatically closed when it exits the ctx manager

第四:遵循代码的PEP-8样式标准。所有阅读你的代码的人都会感谢你。你知道吗

I got [...] a 'stop iteration' error.

这很正常;您说过您正在使用next()函数。迭代器和next()引发StopIteration,以表示它们无法从正在迭代的集合中生成更多元素,并且此迭代过程应该停止。你知道吗

引用the docs

exception StopIteration

Raised by built-in function next() and an iterator‘s __next__() method to signal that there are no further items produced by the iterator.

相关问题 更多 >