我正在尝试编写一个备份脚本,其中一部分我正在考虑删除目录中具有相同名称的现有文件,我正在将数据备份到其中,因此我没有数千个具有相同名称的文件。我想删除旧文件,然后备份该文件的新版本。我计划每周使用 crontab 进行一次或两次备份。到目前为止,我有以下内容:
for files in os.walk(BACKUP_FROM_PATH):
if files.isfile():
if files.name in BACKUP_TO_PATH: # checks if a file with the same name is already in the backup dir
os.remove(files)
removed.append(files)
elif files.isdir():
for files2 in os.walk(files):
if files2.isfile():
if files2.name in BACKUP_FROM_PATH:
os.remove(files2)
removed.append(files2)
return removed
我也有以下选择:
for files, dirs, root in os.walk(BACKUP_FROM_PATH):
for currentFile in files:
if currentFile in BACKUP_FROM_PATH):
os.remove(os.path.join(root, currentFile))
removed.append(currentFile)
return removed
我很好奇做简单的 os.remove 和做 os.remove(os.path.join(root, currentFile)) 之间的区别。我见过人们提到两种方式,并想知道是否首选一种方式或他们的行为方式有何不同。