Home > Mobile >  Delete folder or directory using API (django)
Delete folder or directory using API (django)

Time:05-10

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.

CodePudding user response:

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
  • Related