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
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')
In the comments @ShadowRanger suggest to use shutil.rmtree()
I replaced os.remove()
with shutil.rmtree()
and it worked. Thank you very much @ShadowRanger.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With