更新:啊,好的,我看到问题 - 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
中的文件 - 否则,这将删除文件而不复制它们。
谢谢米克尔,谢谢sendrele – Illusionist 2011-04-04 03:02:58