Как удалить все файлы в папке python
Перейти к содержимому

Как удалить все файлы в папке python

  • автор:

Delete (Remove) Files and Directories in Python

In this tutorial, you’ll learn how to delete files or directories in Python.

After reading this tutorial, you’ll learn: –

  • Deleting file using the os module and pathlib module
  • Deleting files from a directory
  • Remove files that match a pattern (wildcard)
  • Delete empty directory
  • Delete content of a directory (all files and sub directories)

Sometimes we need to delete files from a directory that is no longer needed. For example, you are storing monthly inventory data in a file. You may want to delete any existing data files before creating a new data file each month.

Also, after some time, the application needs to delete its old log files.

In this tutorial, we will use the following Python functions to delete files and folders.

Function Description
os.remove(‘file_path’) Removes the specified file.
os.unlink(‘file_path’) Removes the specified file. Useful in UNIX environment.
pathlib.Path(«file_path»).unlink() Delete the file or symbolic link in the mentioned path
os.rmdir(’empty_dir_path’) Removes the empty folder.
pathlib.Path(empty_dir_path).rmdir() Unlink and delete the empty folder.
shutil.rmtree(‘dir_path’) Delete a directory and the files contained in it.

Functions to delete files and folders

Note:

  • All above functions delete files and folders permanently.
  • The pathlib module was added in Python 3.4. It is appropriate when your application runs on a different operating systems.

Table of contents

How to Delete a File in Python

Python provides strong support for file handling. We can delete files using different methods and the most commonly used one is the os.remove() method. Below are the steps to delete a file.

    Find the path of a file

We can delete a file using both relative path and absolute path. The path is the location of the file on the disk.
An absolute path contains the complete directory list required to locate the file. And A relative path includes the current directory and then the file name.
For example, /home/Pynative/reports/samples.txt is an absolute path to discover the samples.txt.

The OS module in Python provides methods to interact with the Operating System in Python. The remove () method in this module is used to remove/delete a file path.
First, import the os module and Pass a file path to the os.remove(‘file_path’) function to delete a file from a disk

Import the shutil module and pass the directory path to shutil.rmtree(‘path’) function to delete a directory and all files contained in it.

Example: Remove File in Python

The following code explains how to delete a file named “sales_1.txt”.

Let’s assume we want to delete the sales_1.txt file from the E:\demos\files\ directory. Right now, this directory contains the following files:

  1. sales_1.txt
  2. sales_2.csv
  3. profits.txt
  4. revenue.txt

Remove file with relative path

Remove file with absolute path

Our code deleted two files. Here is a list of the remaining files in our directory:

  • profits.txt
  • revenue.txt

Before deleting a file

Before deleting a file

After deleting a file

After deleting a file

Understand the os.remove() method

Syntax:

Pass file path to the os.remove(‘file_path’) function to delete a file from a disk

The following are the parameters that we need to pass.

  • path – A relative or absolute path for the file object generally in string format.
  • dir_fd – A directory representing the location of the file. The default value is none and this value is ignored in the case of an absolute path.

If the passed file path is a directory, an OSError will be raised

Check if File Exist Before Deleting It

A FileNotFoundError will be raised if the file is not found in the path so it is advisable to check if the file exists before deleting it.

This can be achieved in two ways:

  • os.path.exists(«file path») function to check if file exists.
  • Use exception handling.

Example 1:

Note: Exception handling is recommended over file check because the file could be removed or changed in between. It is the Pythonic way to delete a file that may or may not exist.

Example 2: Exception handling

Remove File Using os.unlink() method

If you are using the UNIX operating system use the unlink() method available in the OS module, which is similar to the remove() except that it is more familiar in the UNIX environment.

  • path – A relative or absolute path for the file object generally in string format.
  • dir_fd – A directory representing the location of the file. The default value is none and this value is ignored in the case of an absolute path.

Let us see the code for deleting the file “profits.txt” which is in the current execution path.

Pathlib Module to Remove File

The pathlib module offers classes representing filesystem paths with semantics appropriate for different operating systems. Thus, whenever we need to work with files in multiple environments, we can use the pathlib module.

The pathlib module was added in Python 3.4. The pathlib.path.unlink() method in the pathlib module is used to remove the file in the mentioned path.

Also, it takes one extra parameter, namely missing_ok=False . If the parameter is set to True, then the pathlib module ignores the File Not Found Error. Otherwise, if the path doesn’t exist, then the FileNotFoundError will be raised.

Let us see the code for deleting the file “profits.txt” which is present in the current execution path.

  • Import a pathlib module
  • Use pathlib.Path() method to set a file path
  • Next, to delete a file call the unlink() method on a given file path.

Delete all Files from a Directory

Sometimes we want to delete all files from a directory without deleting a directory. Follow the below steps to delete all files from a directory.

    using os.listdir(path) function. It returns a list containing the names of the files and folders in the given directory.
  • Iterate over the list using a for loop to access each file one by one
  • Delete each file using the os.remove()

Example:

Delete an Empty Directory (Folder) using rmdir()

While it is always the case that a directory has some files, sometimes there are empty folders or directories that no longer needed. We can delete them using the rmdir() method available in both the os module and the pathlib module.

Using os.rmdir() method

In order to delete empty folders, we can use the rmdir() function from the os module.

The following are the parameters that we need to pass to this method.

  • path – A relative or absolute path for the directory object generally in string format.
  • dir_fd – File directory. The default value is none, and this value is ignored in the case of an absolute path.

Note: In case if the directory is not empty then the OSError will be thrown.

Output

Use pathlib.Path.rmdir()

The rmdir() method in the pathlib module is also used to remove or delete an empty directory.

  • First set the path for the directory
  • Next, call the rmdir() method on that path

Let us see an example for deleting an empty directory called ‘Images’.

Delete a Non-Empty Directory using shutil

Sometimes we need to delete a folder and all files contained in it. Use the rmtree() method of a shutil module to delete a directory and all files from it. See delete a non-empty folder in Python.

The Python shutil module helps perform high-level operations in a file or collection of files like copying or removing content.

Parameters:

  • path – The directory to delete. The symbolic links to a directory are not acceptable.
  • ignore_errors – If this flag is set to true, then the errors due to failed removals will be ignored. If set to true, the error should be handler by the function passed in the one error attribute.

Note: The rmtree() function deletes the specified folder and all its subfolders recursively.

Consider the following example for deleting the folder ‘reports’ that contains image files and pdf files.

Output

Get the proper exception message while deleting a non-empty directory

In order to get the proper exception message we can either handle it in a separate function whose name we can pass in the oneerror parameter or by catching it in the try-except block.

Final code: To delete File or directory

Deleting Files Matching a Pattern

For example, you want to delete files if a name contains a specific string.

The Python glob module, part of the Python Standard Library, is used to find the files and folders whose names follow a specific pattern.

The glob.glob() method returns a list of files or folders that matches the pattern specified in the pathname argument.

This function takes two arguments, namely pathname, and recursive flag ( If set to True it will search files recursively in all subfolders)

We can use the wildcard characters for the pattern matching, and the following is the list of the wildcard characters used in the pattern matching.

  • Asterisk ( * ): Matches zero or more characters
  • Question Mark ( ? ) matches exactly one character
  • We can specify a range of alphanumeric characters inside the [] .

Example: Deleting Files with Specific Extension

On certain occasions, we have to delete all the files with a particular extension.

  • Use glob() method to find all text files in a folder
  • Use for loop to iterate all files
  • In each iteration, delete single file.

Let us see few examples to understand how to use this to delete files that match a specific pattern.

Example

Delete file whose name starts with specific string

Delete file whose name contains a specific letters

We can give a range of characters as the search string by enclosing them inside the square brackets ( [] ).

The following example will show how to delete files whose name contains characters between a-g.

Deleting Files Matching a Pattern from all Subfolders

While the glob() function finds files inside a folder, it is possible to search for files inside the subfolders using the iglob() function which is similar to the glob() function.

The iglob() function returns iterator options with the list of files matching a pattern inside the folder and its subfolder.

We need to set the recursive flag to True when we search for the files in subdirectories. After the root folder name, we need to pass ** for searching inside the subdirectories.

Output

Conclusion

Python provides several modules for removing files and directories.

To delete Files: –

  • Use os.remove() and os.unlink() functions to delete a single file
  • Use pathlib.Path.unlink() to delete a file if you use Python version > 3.4 and application runs on different operating systems.

To delete Directories

  • Use os.rmdir() or pathlib.Path.rmdir() to delete an empty directory
  • use the shutil.rmtree() to recursively delete a directory and all files from it.

Take due care before removing files or directories because all the above functions delete files and folders permanently.

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!

Related Tutorial Topics:

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

Python Delete All Files in a Folder

This tutorial shows you how to delete all files in a folder using Python. In Python, the OS module allows you to delete a single file using the remove() method. Surprisingly, there’s no default support for deleting all files inside a directory in the Python OS module so we’ll walk through several strategies to help you do it. We’ll demonstrate deleting all files in a folder using the OS module, the Pathlib module and Shutil module of Python.

Creating the Directory Structure

Let’s first create some dummy files in a directory. We’ll study how to remove these files in the next sections. The following script first changes the current working directory for your Python script and populates the directory with 5 files of different types. Our dummy files will be in the C:\main directory folder. You can change this path for your specific project.

Output:

Delete All Files using the OS Module

The most basic method of deleting all files in a folder is by iterating through all the file paths and deleting them one by one. The os.listdir() method returns a list containing paths of all the files in a directory. You can then use a for loop to iterate through the path list and delete each file one by one using the remove() method.

Here’s how you would do that:

The empty list in the output shows that all files were removed from our working directory.

In addition to using the for loop you can also use list comprehension to remove all files from a folder, like we do in the following script:

If you want to remove specific file types, you can use the endswith() method and pass it the file extension while removing files. The script below will remove all files with .png extension, and it will keep all the other files intact.

The output below confirms all the PNG files were removed and all the other files still remain.

Output:

You’ll often see situations where a folder contains both files and sub-folders. If you want to remove files but keep the subfolders, you can check the path type using the isfile() method from the os module.

Let’s first create some dummy files and folders (directories) inside our current working directory.

Your current working directory now contains 5 files and 2 folders, dir1 and dir2 .

Output:

The following script uses the isfile() method to check if the path points to a file or not, the file is only deleted if the isfile() method returns true.

The output shows that all files are removed and only folders are left in your current working directory. Any files in those subfolders remain, as well.

Output:

To delete empty subfolders, you can iterate through the path list and use the rmdir() method. Here’s an example:

Keep in mind that, just like with shell commands on a terminal, rmdir only works if the subfolders are empty.

Get Our Python Developer Kit for Free

I put together a Python Developer Kit with over 100 pre-built Python scripts covering data structures, Pandas, NumPy, Seaborn, machine learning, file processing, web scraping and a whole lot more — and I want you to have it for free. Enter your email address below and I’ll send a copy your way.

Delete All Files using the Pathlib Module

The OS module isn’t the only way to remove files from a directory. You can also use the Pathlib module’s Path class to remove all files from a folder. Here’s how it works.

First, you have to create an object of the Path class and pass it your parent folder path containing all your files.

Next, you need to call the glob() method of the Path class object and pass it the type of file you want removed. The glob() method returns a list containing paths of files and folders inside a parent folder. Passing «*» to the glob() method returns all files.

Finally, you can iterate through the list returned by the glob() method and remove files using the unlink() method. You’re able to check if a path points to a file via the is_file() method. The following script removes all files from the path C:\main directory , but keeps files in subfolders.

Just like we did with the OS module, you can specify file types as parameter values of the glob() method. As an example, the following script only removes the PNG type files.

Delete All Files and Subfolders using the Shutil Module

Finally, if you want to delete all files and directories, including subfolders, you can use the rmtree() method from the Shutil module. The following script removes the directory C:\main directory and all its files, folders, and subfolders.

Since, the rmtree() method removes the parent folder too, you can call mkdir() method from the OS module and pass it the path to your parent folder to create an empty folder of the same name. Here’s an example:

Get Our Python Developer Kit for Free

I put together a Python Developer Kit with over 100 pre-built Python scripts covering data structures, Pandas, NumPy, Seaborn, machine learning, file processing, web scraping and a whole lot more — and I want you to have it for free. Enter your email address below and I’ll send a copy your way.

How to delete the contents of a folder?

How can I delete the contents of a local folder in Python?

The current project is for Windows, but I would like to see *nix also.

martineau's user avatar

27 Answers 27

Mark Amery's user avatar

You can simply do this:

You can of course use an other filter in you path, for example : /YOU/PATH/*.txt for removing all text files in a directory.

John Smith's user avatar

You can delete the folder itself, as well as all its contents, using shutil.rmtree :

shutil.rmtree(path, ignore_errors=False, onerror=None)

Delete an entire directory tree; path must point to a directory (but not a symbolic link to a directory). If ignore_errors is true, errors resulting from failed removals will be ignored; if false or omitted, such errors are handled by calling a handler specified by onerror or, if that is omitted, they raise an exception.

Mark Amery's user avatar

Expanding on mhawke’s answer this is what I’ve implemented. It removes all the content of a folder but not the folder itself. Tested on Linux with files, folders and symbolic links, should work on Windows as well.

I’m surprised nobody has mentioned the awesome pathlib to do this job.

If you only want to remove files in a directory it can be a oneliner

To also recursively remove directories you can write something like this:

Leland Hepworth's user avatar

Using rmtree and recreating the folder could work, but I have run into errors when deleting and immediately recreating folders on network drives.

The proposed solution using walk does not work as it uses rmtree to remove folders and then may attempt to use os.unlink on the files that were previously in those folders. This causes an error.

The posted glob solution will also attempt to delete non-empty folders, causing errors.

I suggest you use:

  • removes all symbolic links
    • dead links
    • links to directories
    • links to files

    As many other answers, this does not try to adjust permissions to enable removal of files/directories.

    Mark Amery's user avatar

    Earlier versions of Python:

    Notes: in case someone down voted my answer, I have something to explain here.

    1. Everyone likes short ‘n’ simple answers. However, sometimes the reality is not so simple.
    2. Back to my answer. I know shutil.rmtree() could be used to delete a directory tree. I’ve used it many times in my own projects. But you must realize that the directory itself will also be deleted by shutil.rmtree() . While this might be acceptable for some, it’s not a valid answer for deleting the contents of a folder (without side effects).
    3. I’ll show you an example of the side effects. Suppose that you have a directory with customized owner and mode bits, where there are a lot of contents. Then you delete it with shutil.rmtree() and rebuild it with os.mkdir() . And you’ll get an empty directory with default (inherited) owner and mode bits instead. While you might have the privilege to delete the contents and even the directory, you might not be able to set back the original owner and mode bits on the directory (e.g. you’re not a superuser).
    4. Finally, be patient and read the code. It’s long and ugly (in sight), but proven to be reliable and efficient (in use).

    Here’s a long and ugly, but reliable and efficient solution.

    It resolves a few problems which are not addressed by the other answerers:

    8 команд для Python по работе с файлами и файловой системой, которые обязательно нужно знать

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

    Эта статья предназначена как раз для начинающих разработчиков. В ней описаны 8 крайне важных команд для работы с файлами, папками и файловой системой в целом. Все примеры из этой статьи размещены в Google Colab Notebook (ссылка на ресурс — в конце статьи).

    Показать текущий каталог

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

    Относительный путь хорош тем, что работает для всех пользователей, с любыми системами, количеством дисков и так далее.

    Так вот, для того чтобы показать текущий каталог, нужна встроенная в Python OS-библиотека:

    Ее легко запомнить, так что лучше выучить один раз, чем постоянно гуглить. Это здорово экономит время.

    Имейте в виду, что я использую Google Colab, так что путь /content является абсолютным.

    Проверяем, существует файл или каталог

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

    Функция os.path.exists () принимает аргумент строкового типа, который может быть либо именем каталога, либо файлом.

    В случае с Google Colab при каждом запуске создается папка sample_data. Давайте проверим, существует ли такой каталог. Для этого подойдет следующий код:

    Эта же команда подходит и для работы с файлами:

    Если папки или файла нет, команда возвращает false.

    Объединение компонентов пути

    В предыдущем примере я намеренно использовал слеш "/" для разделителя компонентов пути. В принципе это нормально, но не рекомендуется. Если вы хотите, чтобы ваше приложение было кроссплатформенным, такой вариант не подходит. Так, некоторые старые версии ОС Windows распознают только слеш "\" в качестве разделителя.

    Но не переживайте, Python прекрасно решает эту проблему благодаря функции os.path.join (). Давайте перепишем вариант из примера в предыдущем пункте, используя эту функцию:

    Создание директории

    Ну а теперь самое время создать директорию с именем test_dir внутри рабочей директории. Для этого можно использовать функцию
    os.mkdir():

    Давайте посмотрим, как это работает на практике.

    Если же мы попытаемся создать каталог, который уже существует, то получим исключение.

    Именно поэтому рекомендуется всегда проверять наличие каталога с определенным названием перед созданием нового:

    Еще один совет по созданию каталогов. Иногда нам нужно создать подкаталоги с уровнем вложенности 2 или более. Если мы все еще используем os.mkdir (), нам нужно будет сделать это несколько раз. В этом случае мы можем использовать os.makedirs (). Эта функция создаст все промежуточные каталоги так же, как флаг mkdir -p в системе Linux:

    Вот что получается в результате.

    Показываем содержимое директории

    Еще одна полезная команда — os.listdir(). Она показывает все содержимое каталога.

    Команда отличается от os.walk (), где последний рекурсивно показывает все, что находится «под» каталогом. os.listdir () намного проще в использовании, потому что просто возвращает список содержимого:

    В некоторых случаях нужно что-то более продвинутое — например, поиск всех CSV-файлов в каталоге «sample_data». В этом случае самый простой способ — использовать встроенную библиотеку glob:

    Перемещение файлов

    Самое время попробовать переместить файлы из одной папки в другую. Рекомендованный способ — еще одна встроенная библиотека shutil.
    Сейчас попробуем переместить все CSV-файлы из директории «sample_data» в директорию «test_dir». Ниже — пример кода для выполнения этой операции:

    Кстати, есть два способа выполнить задуманное. Например, мы можем использовать библиотеку OS, если не хочется импортировать дополнительные библиотеки. Как os.rename, так и os.replace подходят для решения задачи.

    Но обе они недостаточно «умные», чтобы позволить перемесить файлы в каталог.

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

    Здесь функция os.path.basename () предназначена для извлечения имени файла из пути с любым количеством компонентов.

    Другая функция, os.replace (), делает то же самое. Но разница в том, что os.replace () не зависит от платформы, тогда как os.rename () будет работать только в системе Unix / Linux.

    Еще один минус — в том, что обе функции не поддерживают перемещение файлов из разных файловых систем, в отличие от shutil.

    Поэтому я рекомендую использовать shutil.move () для перемещения файлов.

    Копирование файлов

    Аналогичным образом shutil подходит и для копирования файлов по уже упомянутым причинам.

    Если нужно скопировать файл README.md из папки «sample_data» в папку «test_dir», поможет функция shutil.copy():

    Удаление файлов и папок

    Теперь пришел черед разобраться с процедурой удаления файлов и папок. Нам здесь снова поможет библиотека OS.

    Когда нужно удалить файл, нужно воспользоваться командой os.remove():

    Если требуется удалить каталог, на помощь приходит os.rmdir():

    Однако он может удалить только пустой каталог. На приведенном выше скриншоте видим, что удалить можно лишь каталог level_3. Что если мы хотим рекурсивно удалить каталог level_1? В этом случае зовем на помощь shutil.

    Функция shutil.rmtree() сделает все, что нужно:

    Пользоваться ею нужно с осторожностью, поскольку она безвозвратно удаляет все содержимое каталога.

    Собственно, на этом все. 8 важных операций по работе с файлами и каталогами в среде Python мы знаем. Что касается ссылки, о которой говорилось в анонсе, то вот она — это Google Colab Network с содержимым, готовым к запуску.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *