Питон удалить содержимое папки

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.
Читайте также:  Php while select array

Best practice

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

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)) 

You can use the built-in pathlib module (requires Python 3.4+, but there are backports for older versions on PyPI: pathlib , pathlib2 ).

To remove a file there is the unlink method:

import pathlib path = pathlib.Path(name_of_file) path.unlink() 

Or the rmdir method to remove an empty folder:

import pathlib path = pathlib.Path(name_of_folder) path.rmdir() 

@Pranasas Unfortunately it seems there is nothing (natively) in pathlib that can handle deleting non-empty directories. However you could use shutil.rmtree . It has been mentioned in several of the other answers so I haven’t included it.

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.

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.

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() 

Источник

Удаление содержимого папки в Python

Существуют ситуации, когда в процессе работы с файловой системой на языке Python возникает необходимость удалить все файлы в указанной директории. Это может быть полезно, например, при очистке временной папки перед новым запуском программы.

В Python для работы с файловой системой есть модуль os . Для удаления файлов внутри директории можно использовать функцию os.remove() . Однако, прежде чем удалить файл, нужно получить его полный путь. Это можно сделать с помощью функции os.path.join(path, file) , где path — путь к директории, а file — имя файла.

import os def delete_files_in_folder(folder_path): for filename in os.listdir(folder_path): file_path = os.path.join(folder_path, filename) try: if os.path.isfile(file_path): os.remove(file_path) except Exception as e: print(f'Ошибка при удалении файла . ')

В этом коде функция delete_files_in_folder принимает путь к папке folder_path и удаляет все файлы внутри неё. Если в процессе удаления возникнет исключение, оно будет залогировано в консоли.

Если же нужно удалить все файлы и поддиректории внутри указанной папки, то можно воспользоваться модулем shutil и его функцией shutil.rmtree() , а затем создать пустую директорию с помощью os.mkdir() .

import shutil import os def delete_everything_in_folder(folder_path): shutil.rmtree(folder_path) os.mkdir(folder_path)

В этом коде функция delete_everything_in_folder полностью удаляет папку по указанному пути и все её содержимое, а затем создаёт новую пустую папку с тем же именем.

Обратите внимание, что удаление файлов и папок — это необратимая операция, поэтому перед использованием этих функций убедитесь, что вы не удалите важные данные.

Источник

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