[英]FileNotFoundError: when creating new file
Want to backup files to different directory. 要将文件备份到其他目录。
As the files are backed up quite nicely, but when program encounters a folders it fetches a error: 由于文件备份非常好,但是当程序遇到文件夹时,它将获取错误:
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'
My code is: 我的代码是:
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)
Use shutil.copytree()
instead. 请改用
shutil.copytree()
。 Something like: 就像是:
shutil.copytree('.', Newpath)
would do. 会做。
Looks like this: 看起来像这样:
file = os.path.join(Newpath,thefile[2:])
Returns a path that includes a subdirectory name a
that you haven't yet created. 返回包含尚未创建的子目录名称
a
的路径。
This is the path that is returned as problematic in your stacktrace: 这是您的堆栈跟踪中有问题的返回路径:
C:\Users\kemburaj.kemburaj-PC\Documents\backup\a\Appointment Reciept.pdf
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.