我想移动很多文件.这些文件的路径存储在列表中.我想保留整个目录结构,但想将它们移动到另一个文件夹.
例如,文件是D:\ test\test1\test1.txt D:\ test\test1\test2.txt
我想将它们从D:\移到C:\并保留目录结构.我应该怎么做呢?
这是我的代码,它不起作用
import os, fnmatch
import shutil
f=open('test_logs.txt','r') #logs where filenames are stored with filenames as first entry
for line in f:
filename=line.split()
output_file="C:" + filename[0].lstrip("D:")
shutil.move(filename[0],output_file)
Run Code Online (Sandbox Code Playgroud)
我读文件名很好,我可以很好地生成目标文件名但是当我运行它时,它给我一个错误,说"没有这样的文件或目录"(并给出输出文件名的路径).
我想你想要这样的东西:
import sys
import os
import shutil
# terminology:
# path = full path to a file, i.e. directory + file name
# directory = directory, possibly starting with a drive
# file name = the last component of the path
sourcedrive = 'D:'
destdrive = 'C:'
log_list_file = open('test_logs.txt', 'r')
for line in log_list_file:
sourcepath = line.split()[0] # XXX is this correct?
if sourcepath.startswith(sourcedrive):
destpath = sourcepath.replace(sourcedrive, destdrive, 1)
else:
print >>sys.stderr, 'Skipping %s: Not on %s' % (sourcepath, sourcedrive)
continue
destdir = os.path.dirname(destpath)
if not os.path.isdir(destdir):
try:
os.makedirs(destdir)
except (OSError, IOError, Error) as e:
print >>sys.stderr, 'Error making %s: %s' % (destdir, e)
continue
try:
shutil.move(sourcepath, destpath)
except (OSError, IOError, Error) as e:
print >>sys.stderr, 'Error moving %s to %s: %s' % (sourcepath, destpath, e)
Run Code Online (Sandbox Code Playgroud)
如果源目录为空,是否还要删除源目录?