将文件名和大小与部分路径进行比较



我的最终目标是将新文件从位置X同步到位置Y。

源路径为/srv/dev-disk-by-uuid-5a792a17-de43-4e09-9c99-36e48c6c30aa/datafs

目的地路径为/mnt/Usb/DataSync

我想比较源路径及其子文件夹中的所有文件,以准确地作为目标,例如:

/srv/dev-disk-by-uuid-5a792a17-de43-4e09-9c99-36e48c6c30aa/datafs/photo/png21.png

与相同

/mnt/Usb/DataSync/photo/png21.png

因此,在这个例子中,我只想比较photo目录及其文件。

如果这是相同的文件名但大小不同(文件已更改(,我想将文件从源复制到目标。

我搜索了globos.walk,但所有的解决方案都是在文件名是完整路径的情况下,但我只需要部分路径。glob不是我的解决方案,因为它只搜索特定目录中的文件;os.walk不是我的方案,因为需要所有路径。

我的问题:

如果两个文件是相同的文件名,并且有部分路径(如上面的例子-"照片"目录(,我该如何比较?

def SyncFiles(DstDiskPath):
SrcDisk = /srv/dev-disk-by-uuid-5a792a17-de43-4e09-9c99-36e48c6c30aa/datafs/
print("[+] Drive OK, syncing")
for path, CurrentDirectory, files in os.walk(SrcDisk)
for file in files:
if (file in DstDiskPath):
if os.path.getsize((os.path.join(path, file)) != os.path.getsize((os.path.join(path, file))
shutil.copy2((os.path.join(path, file), (os.path.join(DstDiskPath, file)))

只需修剪掉要忽略的部分。

def SyncFiles(DstDiskPath):
# Syntax fix, need quotes around path
SrcDisk = "/srv/dev-disk-by-uuid-5a792a17-de43-4e09-9c99-36e48c6c30aa/datafs/"
print("[+] Drive OK, syncing")
for path, CurrentDirectory, files in os.walk(SrcDisk)
# remove starting point prefix from path and replace it with destination
dstpath = os.path.join(DstDiskPath, path[len(SrcDisk)+1:])
for file in files:
# fix: "file in path" checks if the string is a substring
srcfile = os.path.join(path, file)
dstfile = os.path.join(dstpath, file)
if os.path.exists(dstfile):
if os.path.getsize(srcfile) != os.path.getsize(dstfile):
shutil.copy2(srcfile, dstfile)

不过,文件大小比较并不是检查文件是否已更改的可靠方法。您可能希望使用现有的rsync工具进行备份。

最新更新