我有一些使用shutil.copyfile的python代码:
import os
import shutil
src='C:\Documents and Settings\user\Desktop\FilesPy'
des='C:\Documents and Settings\user\Desktop\\tryPy\Output'
x=os.listdir(src)
a=os.path.join(src,x[1])
shutil.copyfile(a,des)
print a
它给了我一个错误:
IOError: [Errno 13] Permission denied: 'C:\\Documents and Settings\\user\\Desktop\\tryPy\\Output'
为什么我没有权限复制文件?
来自documentation的shutil.copyfile
:
将名为src的文件的内容(无元数据)复制到名为dst的文件中。 dst必须是完整的目标文件名;查看shutil.copy()以获取接受目标目录路径的副本。如果src和dst是相同的文件,则引发Error。目的地位置必须是可写的;否则,将引发IOError异常。如果dst已经存在,它将被替换。使用此功能无法复制特殊文件,如字符或块设备和管道。 src和dst是以字符串形式给出的路径名。
所以我想你需要使用shutil.copy
或将文件名添加到des
:
des = os.path.join(des, x[1])
我建议你使用shutil.copyfile而不是shutil.copy,如果可以的话。
使用shutil.copyfile,您必须考虑写入权限等元数据。
我在这里尝试了所有的东西,但我的代码的问题是关于目标文件夹的权限。我创建了自己的创建目录的功能,
def mkdirs(newdir,mode=777):
try:
os.makedirs(newdir, mode)
except OSError as err:
return err
而不是777,后来我使用'0o777'八进制值,后来使用了shutil.copyfile(target_file,dest_file)
,它工作了!
希望这能帮助那些首先创建目录然后复制文件的人。