我试图在Python 3中编写一个函数,将所有以字符串'halloween'结尾的行写入文件.当我调用这个函数时,我只能得到一行写入输出文件(file_2.txt).任何人都可以指出我的问题在哪里?提前致谢.
def parser(reader_o, infile_object, outfile_object):
for line in reader_o:
if line.endswith('halloween'):
return(line)
with open("file_1.txt", "r") as file_input:
reader = file_input.readlines()
with open("file_2.txt", "w") as file_output:
file_output.write(parser(reader))
Run Code Online (Sandbox Code Playgroud)
def parser(reader_o):
for line in reader_o:
if line.rstrip().endswith('halloween'):
yield line
with open("file_1.txt", "r") as file_input:
with open("file_2.txt", "w") as file_output:
file_output.writelines(parser(file_input))
Run Code Online (Sandbox Code Playgroud)
这被称为发电机.它也可以写成表达式而不是函数:
with open("file_1.txt", "r") as file_input:
with open("file_2.txt", "w") as file_output:
file_output.writelines(line for line in file_input if line.rstrip().endswith('halloween'))
Run Code Online (Sandbox Code Playgroud)
如果你使用的是Python 2.7/3.2,你可以这样做with:
with open("file_1.txt", "r") as file_input, open("file_2.txt", "w") as file_output:
Run Code Online (Sandbox Code Playgroud)
你不需要readlines()对文件进行操作,只是告诉循环迭代打开的文件本身就会做同样的事情.
你的问题是return总是会在第一场比赛中退出循环.yield停止循环,传递出值,然后可以从同一点再次启动发生器.