'Delete folder or directory using API (django)
I have written down a Python script to delete or remove a folder from file directory. The code is below:
import os
import sys
import shutil
base_dir = os.path.dirname(os.path.realpath(__file__))
path = 'media/user110'
try:
path = os.path.join(base_dir, path)
shutil.rmtree(path)
print("Deleted: " + path)
except OSError as e:
print("Error: %s - %s." % (e.filename, e.strerror))
This worked. But it's not working in API using Django.
If I print path it shows '/home/Desktop/my_project/media/user110/
But when I want to do this in API using Django, using same code, and print path I got /media/user110/ and it throw an Exception saying this directory doesn't exist
Now I want to delete or remove file directory using API. I want the solution.
BTW, I am using Linux, and my project will deploy in Linux server.
Solution 1:[1]
It is pretty simple use the below code snippet to delete a folder.
import shutil
import os
from main_app.settings import BASE_DIR
# This is your folder path
file_location = os.path.join(BASE_DIR, 'media/user110')
# Here, lets delete the file
shutil.rmtree(file_location, ignore_errors = False)
# making ignore_errors = True will not raise a FileNotFoundError
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Shahid Tariq |
