Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get a Errno 1 Operation not permitted when the folder is created with full read/write permissions for everyone in Python?

Tags:

python

macos

So I am trying to make my very first python program to automate a task that I have. The first snippet of code is from a python script that makes a new folder at a pre-specified destination and then moves files from their original location to the new folder. This part works. The folder is created like so:

os.makedirs(new_folder, 0o777)

new_folder stores the name, given by the user, of the folder to be created.

The next snippet of code is from another script that does the opposite. It takes the files from the new folder and moves them back to the original folder and it does this successfully. However what doesn't work is what is supposed to happen next. Once moved back, it is supposed to delete the new folder with its content. I tried doing it with this code:

os.chdir(new_path)
os.remove(folder_name)

og_path is just a variable that stores the path of the new folder which should be deleted. folder_name stores well...the folder's name

When I run the full code of the second script everything works; however when it reaches:

os.remove(folder_name)

It gives me this error:

Traceback (most recent call last):
  File "/Users/TVM/Desktop/python/move_file/move_file_reverse.py", line  25, in <module>
os.remove(folder_name)
PermissionError: [Errno 1] Operation not permitted: 'lab3'

Additional Variable Information:

 new_folder = "lab3"
 folder_name = "lab3"
 new_path = "/Users/TVM/Desktop/python/move_file/newloc"

The folder called lab3 is in the folder newloc

like image 951
TVM Avatar asked Oct 03 '17 02:10

TVM


2 Answers

You should use os.rmdir instead of os.remove.

    os.mkdir('mydir')
    os.rmdir('mydir')
    os.path.exists('mydir')

In case if the directory is not empty and you would like to get rid of the whole directory tree starting from the directory you should use:

shutil.rmtree('mydir')
like image 129
Paweł Kozielski-Romaneczko Avatar answered Nov 15 '22 06:11

Paweł Kozielski-Romaneczko


In the comments @ShadowRanger suggest to use shutil.rmtree()

I replaced os.remove() with shutil.rmtree() and it worked. Thank you very much @ShadowRanger.

like image 25
TVM Avatar answered Nov 15 '22 08:11

TVM