In Python, is it possible to write a generators (c

2019-08-23 13:05发布

问题:

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