无法识别 Python 中的循环变量 [英] Not Recognizing Loop Variable in Python

查看:31
本文介绍了无法识别 Python 中的循环变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to delete 38 lines of text after coming across a certain phrase in a .txt file in Python, while still printing the rest of the text.

我目前拥有的代码是

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='')

但是,我不断收到以下错误:

However, I keep getting the following error:

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 循环中它就无法识别行"?另外,有没有更好的方法来执行这种程序?

Does anyone have any suggestions or clues as to why it does not recognize "line" once I've put it inside the for loop below? Additionally, is there a better way to execute this kind of program?

推荐答案

您需要从列表中删除,不能del 行,最简单的方法是写入临时文件并copy after 如果要修改文件,如果只想打印忽略第38行,用print替换write:

You would need to remove from the list, you cannot del the line, the easiest way is to write to a temp file and copy after if you want to modify the file, if you just want to print ignoring the 38 line replace write with print:

 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移动文件:

Then use shutil to move the file:

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 行.

The only potential problem I see is if the phrase is in one of the 38 ignored lines and you should also remove the next 38 lines from there.

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)

这篇关于无法识别 Python 中的循环变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆