Jerome Paulraj
Jerome Paulraj

Reputation: 95

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)

Upvotes: 1

Views: 1337

Answers (2)

hawksbill
hawksbill

Reputation: 51

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.

This is the path that is returned as problematic in your stacktrace:

C:\Users\kemburaj.kemburaj-PC\Documents\backup\a\Appointment Reciept.pdf

Upvotes: 1

fernandezcuesta
fernandezcuesta

Reputation: 2448

Use shutil.copytree() instead. Something like:

shutil.copytree('.', Newpath)

would do.

Upvotes: 2

Related Questions