Python中的For循环结构

2024-04-26 20:45:28 发布

您现在位置:Python中文网/ 问答频道 /正文

在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”文件,但是secund循环的结果在“outfile_2”文件中是空的。在


Tags: 文件inreforreadaslineresult
2条回答

仅当您在两次读取之间将infile再次“倒带”到开始位置:

... infile.read()

infile.seek(0)

... infile.read()

文件很像录音带;当你读到一个读数时,“磁头”会沿着磁带移动并返回数据。file.seek()将读取的“head”移到另一个位置,infile.seek(0)再次将其移动到开始位置。在

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

^{pr2}$

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)

相关问题 更多 >