Friday, January 26, 2024

[SOLVED] Creating writeable directory in Windows using Python os.makedirs

Issue

I need to create a subdirectory if it doesn't yet exist, then copy some files into it. However, whenever I try, I get a Permission denied error. I've tried chmod, with 777 as well as stat.S_IWRITE, I've tried os.system('attrib -r), but nothing works. Can anyone help me work this one out? I know there is a similar question on the site, but it says to use chmod, which isn't working for me.

Here's my code:

beginpath = "C:\Users\foo"
fullpath = os.path.join(beginpath, foldername)
print fullpath
fullpath = fullpath.replace('\n', '')

##create a folder to hold the deleted files
deleted = os.path.join(fullpath, "Deleted")
print deleted
if not os.path.exists(deleted):
            os.makedirs(deleted)
            os.chmod(deleted, stat.S_IWRITE)
            print "created"



##do some other processing here


oldfile = os.path.join(fullpath, newpagename)
shutil.copyfile(oldfile, deleted)

Solution

I think that shutil.copyfile needs the complete file name of the destination file, not just the directory.

So

shutil.copyfile(oldfile, os.path.join(deleted, newpagename))

should do the trick.



Answered By - MartinStettner
Answer Checked By - Marie Seifert (WPSolving Admin)