Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中的For循环结构_Python_For Loop_Nested - Fatal编程技术网

Python中的For循环结构

Python中的For循环结构,python,for-loop,nested,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'):

在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”文件中是空的。

仅当您在读取之间再次“倒带”
infle
到开始:

... infile.read()

infile.seek(0)

... infile.read()
文件很像录音带;读取时,读取“头”沿磁带移动并返回数据
file.seek()

不过,您最好只阅读一次该文件:

infle.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)

你可以用理解来简化这两个循环!太多了!!现在可以将infle.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)