python - Python 中的 For 循环结构

标签 python for-loop nested

Python中的for循环逻辑是否可能如下?:

with  open("file_r", "r") as infile, open("file_1", 'w') as outfile_1, open("file_2", 'w') as outfile_2: 
    for result in re.findall('somestring(.*?)\}', infile.read(), re.S):
       for line in result.split('\n'):
           outfile_1.write(line) 

    for result in re.findall('sime_other_string(.*?)\}', infile.read(), re.S):
       for line in result.split('\n'):
           outfile_2.write(line)

我这么问是因为第一个 foo 循环的结果写入了“outfile_1”文件,但第二个循环的结果在“outfile_2”文件中为空。

最佳答案

infile.read() 保存到变量中,否则文件将在第一个循环本身中完成。说:

with  open("file_r", "r") as infile, open("file_1", 'w') as outfile_1, open("file_2", 'w') as outfile_2: 
    contents = infile.read()

    for result in re.findall('somestring(.*?)\}', contents, re.S):
       for line in result.split('\n'):
           outfile_1.write(line) 

    for result in re.findall('sime_other_string(.*?)\}', contents, re.S):
       for line in result.split('\n'):
           outfile_2.write(line)

关于python - Python 中的 For 循环结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21876430/

相关文章:

css - LESS 中带有选择器的嵌套规则?

java - 使用 super 关键字的内部类继承

python - 简单的python多处理池脚本错误

python - Pyparsing 在上下文中运行

Javascript,比较数组中的元素,如果为 true 则执行函数

java - 在 For 循环中使用 Try/Catch

javascript - 带有附加下拉菜单的 Angular 菜单项根本不显示

python - 如何创建在Python CDK中引用自身的API网关资源策略?

python - 位串相似度得分

arrays - Bash 数组保存