Python函数只写一行到文件的问题
我正在尝试用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))
相关问题:
3 个回答
0
也许你的解析函数应该是一个生成器。目前它只被调用一次,并返回第一行包含“万圣节”的内容。
像下面这样:
def parser(reader_o):
for line in reader_o:
if line.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))
0
line.endswith('halloween') 这个方法可能只在文件的最后一行有效,因为其他行的末尾都有换行符。首先要用 rstrip 去掉这一行末尾的换行符。另外,建议用 yield 代替 return。
if line.rstrip().endswith('halloween'):
yield line
需要注意的是,这样做也会把行末的空格去掉,这可能是你想要的,也可能不是。
你还需要修改你的消费者代码来
with open("file_2.txt", "w") as file_output:
for ln in parser(reader):
file_output.write(ln)
6
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))
这被称为生成器。它也可以用表达式的方式来写,而不是用函数的方式:
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'))
如果你使用的是Python 2.7或3.2版本,可以这样写两个with:
with open("file_1.txt", "r") as file_input, open("file_2.txt", "w") as file_output:
你不需要对文件使用readlines(),直接告诉循环去遍历打开的文件就能达到同样的效果。
你的问题在于,return会在找到第一个匹配项后就退出循环。而yield则是暂停循环,返回一个值,然后生成器可以从同一个地方继续开始。