如何将生成器的输出写入文本文件?
difflib.context_diff
方法返回一个生成器,向您显示 2 个比较字符串的不同行。如何将结果(比较)写入文本文件?
在此示例代码中,我希望文本文件中从第 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
提前致谢!
The difflib.context_diff
method returns a generator, showing you the different lines of 2 compared strings. 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.
>>> 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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请参阅 文档了解
file.writelines()
。说明:
with
是一个上下文管理器:它负责在完成后关闭文件。这不是必要的,但却是一个很好的做法——你也可以这样做然后调用
output.close()
或让 Python 为您执行此操作(当内存管理器收集output
时)。"w"
表示您正在以写入模式打开文件,而不是"r"
(默认为读取)。您还可以在此处放置各种其他选项(+
表示追加,b
表示二进制 iirc)。writelines
接受任何可迭代的字符串并将它们写入文件对象,一次一个。这与for line in diff: output.write(line)
相同,但更简洁,因为迭代是隐式的。See the documentation for
file.writelines()
.Explanation:
with
is a context manager: it handles closing the file when you are done. It's not necessary but is good practice -- you could just as well doand then either call
output.close()
or let Python do it for you (whenoutput
is collected by the memory manager).The
"w"
means that you are opening the file in write mode, as opposed to"r"
(read, the default). There are various other options you can put here (+
for append,b
for binary iirc).writelines
takes any iterable of strings and writes them to the file object, one at a time. This is the same asfor line in diff: output.write(line)
but neater because the iteration is implicit.