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. 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!
with open(..., "w") as output:
diff = context_diff(...)
output.writelines(diff)
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 dooutput = open(..., "w")
and 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.
f = open(filepath, 'w')
for line in context_diff(s1, s2, fromfile='before.py', tofile='after.py'):
f.write("%s\n" %line)
f.close()
精彩评论