【问题标题】:For Loop Structure in PythonPython中的for循环结构
【发布时间】:2014-02-19 09:39:00
【问题描述】:

在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)

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

【问题讨论】:

    标签: python for-loop nested


    【解决方案1】:

    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)
    

    【讨论】:

    • 你可以使用理解来简化这两个循环。
    • 噢!多谢!!它现在可以将 infile.read() 保存到变量中!
    【解决方案2】:

    仅当您在两次读取之间“倒带”infile 重新开始时:

    ... infile.read()
    
    infile.seek(0)
    
    ... infile.read()
    

    文件很像录音带;当您读取读数时,“磁头”会沿着磁带移动并返回数据。 file.seek() 将阅读“头”移动到不同的位置,infile.seek(0) 将其再次移动到开头。

    不过,您最好读一次

    content_of_infile = infile.read()
    
    for result in re.findall('somestring(.*?)\}', content_of_infile, re.S):
        # ...
    
    for result in re.findall('sime_other_string(.*?)\}', contents_of_infile, re.S):
        # ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-18
      相关资源
      最近更新 更多