简体   繁体   English

Python中for循环选项的结尾?

[英]End of for loop options in Python?

What else can I do at the end other than printing this out to a file? 除了将其打印到文件之外,我最后还能做什么? I don't know any other way to end a for loop and I don't want to have unnecessary files all over the place. 我不知道有什么其他方法可以结束for循环,而且我也不想到处都是不必要的文件。 As an example: 举个例子:

data = open(filename, "r")
found = open("Found.txt", "w")

for line in data:
    if re.match("(.*)(background-color:red)(.*)", line):
        print >> found, line,

I don't WANT to save found at the end...but I don't know how else to take the matched data and do anything with it. 我不希望保存最后found的内容...但是我不知道如何获取匹配的数据并对它进行任何处理。 I've been beating my face on the desk for hours, searched all over the place and I have no idea. 我一直在桌上打着脸好几个小时,到处搜寻,却一无所知。 Seems so basic...lol 似乎很基础...

Please help... 请帮忙...

Use break to exit from a loop. 使用break退出循环。 And why do you need an output file? 为什么需要输出文件? (by the way: that's not the correct way to write to a file). (顺便说一句:这不是写入文件的正确方法)。 Just print the line, if that's what you intend: 如果您要这样做,只需打印该行即可:

for line in data:
    if re.match("(.*)(background-color:red)(.*)", line):
        print line
        break

Or save the line in a variable, for using it later. 或将行保存在变量中,以备后用。 This really depends on what your program is supposed to do, and whether the results of the match need to be persisted for future reference, or if it's enough to save them in-memory for further processing: 这实际上取决于您的程序应该执行的操作,以及是否需要保留匹配结果以供将来参考,或者是否足以将它们保存在内存中以进行进一步处理:

result = None

for line in data:
    if re.match("(.*)(background-color:red)(.*)", line):
        result = line
        break

if result:
    # do something with `result`
    pass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM