Python中的For循环结构
在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'):
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)