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/