我编写了一个Python脚本来比较目录
要求是他们的两个文件
Directory1有内容
1.txt
2.txt
3.txt
4.txt
6.txt
7.txt
9.txt
目录2包含内容
1.txt
2.txt
3.txt
4.txt
5.txt
6.txt
7.txt
8.txt
9.txt
目录2中的所有文件都必须替换为目录1
例如,directory1的输出应该替换为directory2
中的内容 1.txt
2.txt
3.txt
4.txt
5.txt
6.txt
7.txt
8.txt
9.txt
我的脚本是
import os, sys
import filecmp
import re
from distutils import dir_util
import shutil
holderlist=[]
def compareme(dir1, dir2):
dircomp=filecmp.dircmp(dir1,dir2)
only_in_one=dircomp.left_only
diff_in_one=dircomp.diff_files
dirpath=os.path.abspath(dir1)
[holderlist.append(os.path.abspath( os.path.join(dir1,x) )) for x in only_in_one]
[holderlist.append(os.path.abspath( os.path.join(dir1,x) )) for x in diff_in_one]
if len(dircomp.common_dirs) > 0:
for item in dircomp.common_dirs:
compareme(os.path.abspath(os.path.join(dir1,item)), os.path.abspath(os.path.join(dir2,item)))
return holderlist
print holderlist
def main():
if len(sys.argv) > 3:
dir1=sys.argv[1]
dir2=sys.argv[2]
dir3=sys.argv[3]
else:
print "Usage: ", sys.argv[0], "currentdir olddir difference"
sys.exit(1)
if not dir3.endswith('/'): dir3=dir3+'/'
source_files=compareme(dir1,dir2)
dir1=os.path.abspath(dir1)
dir3=os.path.abspath(dir3)
destination_files=[]
new_dirs_create=[]
for item in source_files:
destination_files.append(re.sub(dir1, dir3, item) )
for item in destination_files:
new_dirs_create.append(os.path.split(item)[0])
for mydir in set(new_dirs_create):
if not os.path.exists(mydir): os.makedirs(mydir)
copy_pair=zip(source_files,destination_files)
for item in copy_pair:
if os.path.isfile(item[0]):
shutil.copyfile(item[0], item[1])
if __name__ == '__main__':
main()
但它没有按预期更换文件
答案 0 :(得分:0)
删除 Directory1
中的alle文件 path = Directory1
fnames = os.listdir(path)
for fname in fnames:
fpath = os.path.join(path, fname)
if not stat.S_ISDIR(os.lstat(fpath).st_mode):
os.remove(fpath)
从 Directory2
移动所有文件path = Directory2
fnames = os.listdir(path)
for fname in fnames:
source_fpath = os.path.join(path, fname)
if not stat.S_ISDIR(os.lstat(source_fpath).st_mode):
target_fpath = os.path.join(Directoy1, fname)
os.rename(source_fpath, target_fpath)
答案 1 :(得分:0)
嗯,不清楚为什么使用dir3
,但我会跳过它,因为我认为目标是在dir1
转移差异。如果您想将所有文件从dir2
移至dir1
,我也会为此提供解决方案。
import os
import sys
import shutil
if __name__ == "__main__":
if len(sys.argv) > 3:
dir1=sys.argv[1]
dir2=sys.argv[2]
else:
print "Usage: ", sys.argv[0], "currentdir olddir"
sys.exit(1)
dir1_list = os.listdir(dir1)
dir2_list = os.listdir(dir2)
if dir1_list != dir2_list:
# If you want the different files in dir1 do this:
diff = list(set(dir2_list) - set(dir1_list))
# If you want to move dir2 to dir1 do this:
diff = dir2_list
for file in diff:
shutil.move(os.path.join(dir2, file), os.path.join(dir1, file))