在Python中无法识别循环变量

时间:2015-04-03 15:05:43

标签: python variables

我试图在Python中的.txt文件中遇到某个短语后删除38行文本,同时仍然打印其余文本。

我目前的代码是

with open('text_file.txt','r') as f:
lines = f.readlines()
for line in lines:
    if "certain_phrase" in line:
        for num in range(38):
            del line
    else:
        print(line,end='')

但是,我一直收到以下错误:

Traceback (most recent call last):
  File "C:\<location of file>\python_program.py", line 6, in <module>
    del line
NameError: name 'line' is not defined

有没有人有任何建议或线索,为什么一旦我把它放在下面的for循环中就不能识别“line”?另外,有没有更好的方法来执行这种程序?

4 个答案:

答案 0 :(得分:3)

您需要从列表中删除,您不能del该行,最简单的方法是写入临时文件并在您想要修改文件后复制,如果您只想打印忽略38行替换写入打印:

 with open('in.txt','r') as f,open('temp.txt','w') as temp:
    for line in f:
        if "phrase" in line:
            for i in range(38):
                next(f) # skip 38 lines
        else:
            temp.write(line)

然后使用shutil移动文件:

import shutil

shutil.move("temp.txt","in.txt")

您还可以使用NamedTemporaryFile

from tempfile import NamedTemporaryFile

with open('file.txt','r') as f, NamedTemporaryFile(dir=".",delete=False) as  temp:
    for line in f:
        if "phrase" in line:
            for i in range(38):
                next(f)
        else:
            temp.write(line)

import shutil
shutil.move(temp.name,"file.txt")

我看到的唯一潜在问题是,如果短语位于38个被忽略的行之一中,您还应该从那里删除接下来的38行。

To ignore until a second phrase, keep looping in the inner loop until you find the second phrase then break:

with open('in.txt','r') as f, NamedTemporaryFile(dir=".", delete=False) as temp:
    for line in f:
        if "phrase" in line:
            for _line in f:
                if "phrase2" in _line:
                    break
        else:
            temp.write(line)

答案 1 :(得分:1)

不是尝试从文件中删除行,而是根据旧文件写入新文件。以下使用__next__()来跳过生成器产生的line

with open('text_file.txt','r') as f, open('text_file_mod.txt', 'w') as w:
    for line in f:
        w.write(line)
        if "certain_phrase" in line:
            for num in range(38): # skip 38 lines
                next(f)

如果您是通过交互式解释器执行此操作,则可以通过将next(f)w.write(line)的结果保存到变量来阻止其吐出返回值。

答案 2 :(得分:0)

del line实际上删除了变量line,这意味着当您尝试再次执行此操作时,它不起作用,因为line未定义了。您可以循环索引以查找行,中断,然后删除接下来的38行:

with open('text_file.txt','r') as f:
lines = f.readlines()
for i in range(len(lines)):
    if "certain_phrase" in lines[i]:
        break
    else:
        print(line,end='')
for num in range(38):
    del lines[i]

答案 3 :(得分:0)

with open('temp.txt','r') as fin:
    for line in fin:
        print(line,end="") #you want to print the phrase, right?
        if "certain_phrase" in line:
            for _ in range(38):
                next(line)