我正在编写一个 python 脚本来将目录树中的所有 Excel 文件复制到另一个目录。直截了当,对吧?
好吧,由于某种原因,shutil.copy(或 copy2,或 copyfile)什么都不做,甚至不吐出错误消息。有任何想法吗?
def goFunc(self, event):
print "Starting Go"
for (path, dirs, files) in os.walk(self.path):
print path
print dirs
print files
for every_file in files:
filename = str(path) + str(every_file)
print filename
if filename.endswith('.xlsx'):
print "Copying " + filename + " to " + str(self.path2)
shutil.copyfile(filename, str(self.path2))
print "All DONE!"
所以,除了复制步骤之外,我添加了一个尝试,似乎问题出在那个步骤:
def goFunc(self, event):
print "Starting Go"
for (path, dirs, files) in os.walk(self.path):
print path
print dirs
print files
for every_file in files:
filename = str(path) +'/' + str(every_file)
print filename
if filename.endswith('.xlsx'):
print "Copying " + filename + " to " + str(self.path2)
try:
shutil.copyfile(filename, str(self.path2))
except:
print "Something went wrong"
pass
print "All DONE!"
现在输出是:
Starting Go
/Users/laptop/Desktop
[u'test']
[u'.DS_Store', u'.localized', u'Maytag.xlsx', u'mer.xlsx']
/Users/laptop/Desktop/.DS_Store
/Users/laptop/Desktop/.localized
/Users/laptop/Desktop/Maytag.xlsx
Copying /Users/laptop/Desktop/Maytag.xlsx to /Users/laptop/test
Something went wrong
/Users/laptop/Desktop/mer.xlsx
Copying /Users/laptop/Desktop/mer.xlsx to /Users/laptop/test
Something went wrong
/Users/laptop/Desktop/test
[]
[]
All DONE!
由于某种原因,这些文件仍未被复制。
解决方案:
看起来我需要将文件名添加到目的地。现在它就像一个魅力!感谢大家的时间和帮助。
def goFunc(self, event):
print "Starting Go"
for (path, dirs, files) in os.walk(self.path):
print path
print dirs
print files
for every_file in files:
filename = str(path) +'/' + str(every_file)
print filename
if filename.endswith('.xlsx'):
print "Copying " + filename + " to " + str(self.path2) + '/' + str(every_file)
try:
shutil.copyfile(filename, str(self.path2)+'/'+ str(every_file))
except:
print "Something went wrong"
pass
print "All DONE!"