In Python, is it possible to write a generators (context_diff) output to a text file?

故事扮演 提交于 2019-12-13 03:58:19

问题


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!


回答1:


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

See the documentation for file.writelines().

Explanation:

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

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

  3. writelines takes any iterable of strings and writes them to the file object, one at a time. This is the same as for line in diff: output.write(line) but neater because the iteration is implicit.




回答2:


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

f.close()


来源:https://stackoverflow.com/questions/6613283/in-python-is-it-possible-to-write-a-generators-context-diff-output-to-a-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!