作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
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/
我是一名优秀的程序员,十分优秀!