Python3.7获取两个目录中多个文件的差异
我陷入了创建这个脚本所需的基本逻辑。我正在尝试从本地服务器到远程服务器进行区分。我有用于显式文件名的diff代码,但是现在我需要确定文件是否相同,这样当我在目录中循环时,我就不会在两个完全不同的文件上进行diff。我不太明白我需要使用的逻辑。以下是我的设置:Python3.7获取两个目录中多个文件的差异,python,python-3.x,Python,Python 3.x,我陷入了创建这个脚本所需的基本逻辑。我正在尝试从本地服务器到远程服务器进行区分。我有用于显式文件名的diff代码,但是现在我需要确定文件是否相同,这样当我在目录中循环时,我就不会在两个完全不同的文件上进行diff。我不太明白我需要使用的逻辑。以下是我的设置: source |- test1.xml |-- directory |---- test2.xml |---- test3.xml remote |- test1.xml |-- directory |---- test2.xml |--
source
|- test1.xml
|-- directory
|---- test2.xml
|---- test3.xml
remote
|- test1.xml
|-- directory
|---- test2.xml
|---- test4.xml
我试图弄清楚如何浏览这些目录,匹配哪些目录具有相同的文件名,然后对具有相同文件名的目录进行区分。因此,最终我得到:
patched
|- test1.xml
|-- directory
|---- test2.xml
|---- test3.xml
|---- test4.xml
根据答案和其他资源:
files = filecmp.dircmp('../source', '../repo')
def open_file(filename):
with open(filename) as f:
lines = f.readlines()
return lines
def write_to_new_file(filename, result):
with open(filename, 'w') as f:
lines = f.write(result)
return lines
def report_file_diff(dcmp):
for name in dcmp.diff_files:
print("DIFF file %s found in %s and %s" % (name,
dcmp.left, dcmp.right))
fromfile = os.path.abspath(dcmp.left + '/' + name)
tofile = os.path.abspath(dcmp.right + '/' + name)
source = open_file(fromfile)
repo = open_file(tofile)
diff = difflib.unified_diff(source, repo, fromfile=fromfile, tofile=tofile, lineterm='\n')
result = Colorize.color_diff(diff)
print(''.join(result), end="")
with open('why_is_this_not_working.txt', 'w') as f:
f.write('Because you don\'t know what you are doing\n')
f.write('Because you suck\n')
for name in dcmp.left_only:
print("ONLY SOURCE file %s found in %s" % (name, dcmp.left))
for name in dcmp.right_only:
print("ONLY REMOTE file %s found in %s" % (name, dcmp.right))
for sub_dcmp in dcmp.subdirs.values():
print(sub_dcmp)
report_file_diff(files)
为了管理这个队列,您所需要的就是队列。首先将根目录添加到队列中,然后使用以下逻辑运行一些代码:
太棒了…谢谢你。我使用了这些信息以及我找到的一些其他资源来创建代码。还在写结果,但我会解决的。我更新了我的问题以显示当前代码。