Python: writelines() called for a second time returns empty -


inside python script, use difflib.unified_diff() function receive differences of 2 files. then, following example, call writelines() function write result on screen:

diff = difflib.unified_diff( .... ) sys.stdout.writelines(diff) 

then, want write differences in file, receive empty file. here comes strange part: if exchange order of 2 writelines() calls, correct file empty screen output. same problem can reproduced calling last command twice, this:

diff = difflib.unified_diff( .... ) sys.stdout.writelines(diff) sys.stdout.writelines(diff) 

this print diff once.

i suppose second time function continues same (i.e. last) "line" of diff , doesn't have write. so, there must kind of iterator have reset, couldn't find , how...

difflib.unified_diff() returns generator. produces output once when iterated.

if need write out twice, capture lines in list first:

diff = list(difflib.unified_diff( .... )) sys.stdout.writelines(diff) sys.stdout.writelines(diff) 

from difflib.unified_diff() documentation:

compare a , b (lists of strings); return delta (a generator generating delta lines) in unified diff format.

bold emphasis mine.


Comments