想要将文件备份到不同的目录。
由于文件备份非常好,但是当程序遇到文件夹时会出现错误:
Traceback (most recent call last):
File "C:/Users/kemburaj.kemburaj-PC/Desktop/backup.py", line 16, in <module>
fhand = open(file,'wb')
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\kemburaj.kemburaj-PC\\Documents\\backup\\a\\Appointment Reciept.pdf'
我的代码是:
import os
for dirname, dirs, filename in os.walk("."):
for file in filename:
thefile = os.path.join(dirname,file)
source = open(thefile,'rb')
data = source.read()
source.close()
Newpath = "C:\\Users\kemburaj.kemburaj-PC\Documents\\backup\\" #paste the backup directory path, please check escape characters
if not os.path.exists(Newpath):
os.makedirs(Newpath)
file = os.path.join(Newpath,thefile[2:]) #copy this py file in the directory which is to be backed up
print(file)
fhand = open(file,'wb')
fhand.write(data)
fhand.close()
print("\n\nBackup >",file)
答案 0 :(得分:2)
请改用shutil.copytree()
。
类似的东西:
shutil.copytree('.', Newpath)
会做的。
答案 1 :(得分:1)
看起来像这样:
file = os.path.join(Newpath,thefile[2:])
返回包含尚未创建的子目录名a
的路径。
这是在stacktrace中返回的有问题的路径:
C:\Users\kemburaj.kemburaj-PC\Documents\backup\a\Appointment Reciept.pdf