gpt4 book ai didi

python - Python 中的 For 循环结构

转载 作者:行者123 更新时间:2023-11-30 23:27:55 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com