【问题标题】:Problem in Python with function only writing one line to filePython中的问题,函数仅将一行写入文件
【发布时间】:2011-08-09 14:23:56
【问题描述】:

我正在尝试在 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))

【问题讨论】:

  • 不太确定,是不是因为你用的是return而不是write?
  • 为什么不将输出传递给解析器方法并用 output_file.write(line) 替换 return(line) ?
  • @Bogdan 我认为这不是一个好主意。一种方法应该负责查找匹配项,另一种方法负责编写文件,如果您要拆分它。如果您要让函数进行编写,它应该只做所有事情,就像我的答案的生成器表达式版本一样。

标签: python python-3.x


【解决方案1】:
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))

这称为generator。它也可以写成表达式而不是函数:

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,则可以像这样执行两个 withs:

with open("file_1.txt", "r") as file_input, open("file_2.txt", "w") as file_output:

您无需对文件执行readlines(),只需告诉循环遍历打开的文件本身即可。

您的问题是return 总是会在第一场比赛中退出循环。 yield 停止循环,传递值,然后可以从同一点再次启动生成器。

【讨论】:

  • 谢谢! yield() 解决了我的问题。我非常感谢您的详尽回答和详细解释。你还教了我一些其他很酷的东西,比如两个withs 声明。再次感谢您!
【解决方案2】:

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)

【讨论】:

    【解决方案3】:

    也许你的解析器函数应该是一个生成器。目前它只被调用一次并返回包含“halloween”的第一行。

    如下:

    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))
    

    【讨论】:

      猜你喜欢
      • 2017-12-02
      • 2021-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-15
      • 2020-10-22
      相关资源
      最近更新 更多