简体   繁体   English

如何将生成器的 output 写入文本文件?

[英]How do I write a generator's output to a text file?

The difflib.context_diff method returns a generator, showing you the different lines of 2 compared strings. difflib.context_diff方法返回一个生成器,向您显示 2 个比较字符串的不同行。 How can I write the result (the comparison), to a text file?如何将结果(比较)写入文本文件?

In this example code, I want everything from line 4 to the end in the text file.在这个示例代码中,我想要文本文件中从第 4 行到结尾的所有内容。

>>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n']
>>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n']
>>> for line in context_diff(s1, s2, fromfile='before.py', tofile='after.py'):
...     sys.stdout.write(line)  # doctest: +NORMALIZE_WHITESPACE
*** before.py
--- after.py
***************
*** 1,4 ****
! bacon
! eggs
! ham
  guido
--- 1,4 ----
! python
! eggy
! hamster
  guido

Thanks in advance!提前致谢!

with open(..., "w") as output:
    diff = context_diff(...)
    output.writelines(diff)

See the documentation for file.writelines() .请参阅file.writelines()文档

Explanation:解释:

  1. with is a context manager: it handles closing the file when you are done. with是一个上下文管理器:它处理完成后关闭文件。 It's not necessary but is good practice -- you could just as well do这不是必需的,但这是一种很好的做法——你也可以这样做

    output = open(..., "w")

    and then either call output.close() or let Python do it for you (when output is collected by the memory manager). and then either call output.close() or let Python do it for you (when output is collected by the memory manager).

  2. The "w" means that you are opening the file in write mode, as opposed to "r" (read, the default). "w"表示您正在以写入模式打开文件,而不是"r" (读取,默认值)。 There are various other options you can put here ( + for append, b for binary iirc).您可以在此处放置各种其他选项( +用于 append, b用于二进制 iirc)。

  3. writelines takes any iterable of strings and writes them to the file object, one at a time. writelines接受任何可迭代的字符串并将它们写入文件 object,一次一个。 This is the same as for line in diff: output.write(line) but neater because the iteration is implicit.这与for line in diff: output.write(line)但更简洁,因为迭代是隐式的。

f = open(filepath, 'w')
for line in context_diff(s1, s2, fromfile='before.py', tofile='after.py'):
    f.write("%s\n" %line)

f.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM