我想把一系列的dircmp report_full_disclosure()输出到一个文本文件中,然而report_full_disclosure()格式是一个文本块,它在file.write(comparison_object.report_full_disclosure())上表现得不好,因为file.write()需要单行写入文件。
我尝试过遍历report_full_disclosure()报告,但也不起作用。以前有没有其他人遇到过这种特殊的问题?有没有不同的写入文件的方法?
发布于 2014-05-01 03:11:08
dircmp.filecmp的“报告生成”方法不接受文件对象,它们只使用print语句(或者在Python3版本中使用print()函数)
您可以创建dircmp.filecmp的子类,它接受方法report、report_full_closure和report_partial_closure (如果需要)的文件参数,在每个编写print >>dest, ...的print ...站点。在report_*_closure递归调用的地方,将dest参数向下传递给递归调用。
在我看来,缺少将输出打印到特定文件的能力似乎是一个疏忽,因此在为这些方法添加了一个可选的文件参数并对其进行了彻底测试之后,您可能希望为Python项目贡献自己的力量。
如果您的程序是单线程的,则可以在调用report方法之前将sys.stdout临时替换为目标文件。但是这是一个肮脏和脆弱的方法,如果你认为你的程序永远是单线程的,那可能是愚蠢的。
发布于 2019-01-27 21:44:36
这个问题的答案可以在下面提到的另一个stackoerflow线程中找到,How to redirect 'print' output to a file using python?示例基于上面线程中提供的解决方案为我工作:
>>> import sys
>>> import filecmp
>>> d = dircmp('Documents/dir1','Documents/dir2')
>>> orig_stdout = sys_stdout
>>> orig_stdout = sys.stdout
>>> fo = open('list_of_diff.txt','a+')
>>> sys.stdout = fo
>>> d.report()
>>> sys.stdout = orig_stdout
>>> fo.close()https://stackoverflow.com/questions/23395679
复制相似问题