In Python, I have an application that writes a list to a CSV file, but it has to be almost absolutely sure that the write occurred with no errors or mistakes. The latter is important because although it does catch exceptions from the writer and then the reader, a mistake could happen and the result data be different than the data in the list. However, I have to be abl开发者_高级运维e to show it so that whoever sees the intentionally-cryptic error dialog will then either look at the logs or contact someone who can. In any case, whoever sees the log needs to know how to fix whatever error occurred, and whether such a fix involves the data or me. The actual data in the list is huge by the time it needs to be written to the CSV file, and I cannot put both lists in the log, only the differences between them. What would be the best way to get a string that expresses the differences between such two lists?
Use difflib from Python's standard library. Pulling one of several examples directly from the documentation:
>>> 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
精彩评论