In Python, is it possible to write a generators (context_diff) output to a text file? -
In Python, is it possible to write a generators (context_diff) output to a text file? -
the difflib.context_diff method returns generator, showing different lines of 2 compared strings. how can write result (the comparison), text file?
in illustration code, want line 4 end in text file.
>>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n'] >>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n'] >>> 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") output: diff = context_diff(...) output.writelines(diff)
see documentation file.writelines()
.
explanation:
with
context manager: handles closing file when done. it's not necessary practice -- do
output = open(..., "w")
and either phone call output.close()
or allow python (when output
collected memory manager).
the "w"
means opening file in write mode, opposed "r"
(read, default). there various other options can set here (+
append, b
binary iirc).
writelines
takes iterable of strings , writes them file object, 1 @ time. same for line in diff: output.write(line)
neater because iteration implicit.
python generator difflib
Comments
Post a Comment