Python self delete file

How can I delete a file or folder in Python?

Path objects from the Python 3.4+ pathlib module also expose these instance methods:

If the file doesn’t exist, os.remove() throws an exception, so it may be necessary to check os.path.isfile() first, or wrap in a try .

just for completion. the exception thrown by os.remove() if a file doesn’t exist is FileNotFoundError .

Does os.remove() take multiple arguments to delete multiple files, or do you call it each time for each file?

Python syntax to delete a file

pathlib Library for Python version >= 3.4

file_to_rem = pathlib.Path("/tmp/.txt") file_to_rem.unlink() 

Unlink method used to remove the file or the symbolik link.

  • If missing_ok is false (the default), FileNotFoundError is raised if the path does not exist.
  • If missing_ok is true, FileNotFoundError exceptions will be ignored (same behavior as the POSIX rm -f command).
  • Changed in version 3.8: The missing_ok parameter was added.

Best practice

First, check if the file or folder exists and then delete it. You can achieve this in two ways:

Читайте также:  Пример простой страницы html

EXAMPLE for os.path.isfile

#!/usr/bin/python import os myfile = "/tmp/foo.txt" # If file exists, delete it. if os.path.isfile(myfile): os.remove(myfile) else: # If it fails, inform the user. print("Error: %s file not found" % myfile) 

Exception Handling

#!/usr/bin/python import os # Get input. myfile = raw_input("Enter file name to delete: ") # Try to delete the file. try: os.remove(myfile) except OSError as e: # If it fails, inform the user. print("Error: %s - %s." % (e.filename, e.strerror)) 

Respective output

Enter file name to delete : demo.txt Error: demo.txt - No such file or directory. Enter file name to delete : rrr.txt Error: rrr.txt - Operation not permitted. Enter file name to delete : foo.txt

Python syntax to delete a folder

#!/usr/bin/python import os import sys import shutil # Get directory name mydir = raw_input("Enter directory name: ") # Try to remove the tree; if it fails, throw an error using try. except. try: shutil.rmtree(mydir) except OSError as e: print("Error: %s - %s." % (e.filename, e.strerror)) 

Exception handling is recommended over checking because the file could be removed or changed between the two lines (TOCTOU: en.wikipedia.org/wiki/Time_of_check_to_time_of_use) See Python FAQ docs.python.org/3/glossary.html#term-eafp

shutil.rmtree(path[, ignore_errors[, onerror]]) 

(See complete documentation on shutil) and/or

(Complete documentation on os.)

Here is a robust function that uses both os.remove and shutil.rmtree :

def remove(path): """ param could either be relative or absolute. """ if os.path.isfile(path) or os.path.islink(path): os.remove(path) # remove the file elif os.path.isdir(path): shutil.rmtree(path) # remove dir and all contains else: raise ValueError("file <> is not a file or dir.".format(path)) 

Deleting a file or folder in Python

There are multiple ways to Delete a File in Python but the best ways are the following:

  1. os.remove() removes a file.
  2. os.unlink() removes a file. it is a Unix name of remove() method.
  3. shutil.rmtree() deletes a directory and all its contents.
  4. pathlib.Path.unlink() deletes a single file The pathlib module is available in Python 3.4 and above.
Читайте также:  Tailwind css admin template

os.remove()

Example 1: Basic Example to Remove a File Using os.remove() Method.

import os os.remove("test_file.txt") print("File removed successfully") 

Example 2: Checking if File Exists using os.path.isfile and Deleting it With os.remove

import os #checking if file exist or not if(os.path.isfile("test.txt")): #os.remove() function to remove the file os.remove("test.txt") #Printing the confirmation message of deletion print("File Deleted successfully") else: print("File does not exist") #Showing the message instead of throwig an error 

Example 3: Python Program to Delete all files with a specific extension

import os from os import listdir my_path = 'C:\\Python Pool\\Test' for file_name in listdir(my_path): if file_name.endswith('.txt'): os.remove(my_path + file_name) 

Example 4: Python Program to Delete All Files Inside a Folder

To delete all files inside a particular directory, you simply have to use the * symbol as the pattern string. #Importing os and glob modules import os, glob #Loop Through the folder projects all files and deleting them one by one for file in glob.glob(«pythonpool/*»): os.remove(file) print(«Deleted » + str(file))

os.unlink() is an alias or another name of os.remove() . As in the Unix OS remove is also known as unlink. Note: All the functionalities and syntax is the same of os.unlink() and os.remove(). Both of them are used to delete the Python file path. Both are methods in the os module in Python’s standard libraries which performs the deletion function.

shutil.rmtree()

Example 1: Python Program to Delete a File Using shutil.rmtree()

import shutil import os # location location = "E:/Projects/PythonPool/" # directory dir = "Test" # path path = os.path.join(location, dir) # removing directory shutil.rmtree(path) 

Example 2: Python Program to Delete a File Using shutil.rmtree()

import shutil import os location = "E:/Projects/PythonPool/" dir = "Test" path = os.path.join(location, dir) shutil.rmtree(path) 

pathlib.Path.rmdir() to remove Empty Directory

Pathlib module provides different ways to interact with your files. Rmdir is one of the path functions which allows you to delete an empty folder. Firstly, you need to select the Path() for the directory, and then calling rmdir() method will check the folder size. If it’s empty, it’ll delete it.

Читайте также:  Как проверить строка или число php

This is a good way to deleting empty folders without any fear of losing actual data.

from pathlib import Path q = Path('foldername') q.rmdir() 

Источник

Оцените статью