更新:啊,好的,我看到了问题——shutil.move 不会复制到不存在的目录。要做你想做的事,你必须首先创建新的目录树。由于使用内置移动功能比滚动您自己的复制和删除过程更安全,因此您可以这样做:
with open('test_logs.txt','r') as f:
files_to_copy = [line.split()[0] for line in f]
paths_to_copy = set(os.path.split(filename)[0] for filename in files_to_copy)
def ignore_files(path, names, ptc=paths_to_copy):
return [name for name in names if os.path.join(path, name) not in ptc]
shutil.copytree(src, dst, ignore=ignore_files)
for filename in files_to_copy:
output_file="C:" + filename.lstrip("D:")
shutil.move(filename, output_file)
如果这不起作用,请告诉我
原帖:如果您只想移动部分文件,最好使用shutil.copytree 的ignore 关键字。假设您的文件列表包括完整路径和目录(即['D:\test\test1\test1.txt', 'D:\test\test1\test2.txt', 'D:\test\test1']),创建一个ignore_files 函数并像这样使用它:
files_to_copy = ['D:\test\test1\test1.txt', 'D:\test\test1\test2.txt', 'D:\test\test1']
def ignore_files(path, names, ftc=files_to_copy):
return [name for name in names if os.path.join(path, name) not in ftc]
shutil.copytree(src, dst, ignore=ignore_files)
然后你就可以删除files_to_copy中的文件了:
for f in files_to_copy:
try:
os.remove(f)
except OSError: # can't remove() a directory, so pass
pass
我对此进行了测试 -- 确保包含要复制的路径以及 files_to_copy 中的文件 -- 否则,这将删除文件而不复制它们。