对于Python中的循环结构

时间:2014-02-19 09:39:00

标签: 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)

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

2 个答案:

答案 0 :(得分:3)

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)

答案 1 :(得分:0)

只有当您在两次读取之间再次'infile回放时:

... infile.read()

infile.seek(0)

... infile.read()

文件很像录音带;当你读到一个读数'head'沿着磁带移动并返回数据。 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):
    # ...