如何在脚本中比较python中的两个xml文件?

2024-06-10 00:28:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我是新来的Python。我有一些预定义的xml文件。我有一个生成新xml文件的脚本。我想写一个自动脚本来比较xmls文件并在输出文件中存储不同xml文件名? 提前谢谢


Tags: 文件脚本文件名xmlxmls
3条回答

我想你在找^{} module。你可以这样使用它:

import filecmp
cmp = filecmp.cmp('f1.xml', 'f2.xml')

# Files are equal
if cmp:
    continue
else:
    out_file.write('f1.xml') 

用xml文件替换f1.xmlf2.xml

你说的是按字节比较还是按语义相等比较? (是否<tag attr1="1" attr2="2" />等于<tag attr2="2" attr1="1" />?) 如果要检查语义相等,请查看Xml comparison in Python

在生成xml时,尤其是在对属性使用普通dict的情况下,有时即使使用相同的脚本和相同的输入,属性顺序也可能会混淆。

items()

...

CPython implementation detail: Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions.

基于@Xaranke的回答:

import filecmp

out_file = open("diff_xml_names.txt")
# Not sure what format your filenames will come in, but here's one possibility.
filePairs = [('f1a.xml', 'f1b.xml'), ('f2a.xml', 'f2b.xml'), ('f3a.xml', 'f3b.xml')]

for f1, f2 in filePairs:
    if not filecmp.cmp(f1, f2):
        # Files are not equal
        out_file.write(f1+'\n')

out_file.close()

相关问题 更多 >