Remove file in folder python

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.

import os os.chdir(r"C:\main directory") wd = os.getcwd() all_files = ['IMDB Dataset.csv', 'invoice.txt', 'movie_dataset.csv', 'panda.png', 'receipt.png'] for f in all_files: file = open(f, 'w+') file.close() print(os.listdir())
['IMDB Dataset.csv', 'invoice.txt', 'movie_dataset.csv', 'panda.png', 'receipt.png']

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:

import os os.chdir(r"C:\main directory") all_files = os.listdir() for f in all_files: os.remove(f) print(os.listdir())

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:

import os os.chdir(r"C:\main directory") [os.remove(f) for f in os.listdir()] print(os.listdir())

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.

import os os.chdir(r"C:\main directory") [os.remove(f) for f in os.listdir() if f.endswith(".png")] print(os.listdir())

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

['IMDB Dataset.csv', 'invoice.txt', 'movie_dataset.csv']

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.

import os os.chdir(r"C:\main directory") all_files = ['IMDB Dataset.csv', 'invoice.txt', 'movie_dataset.csv', 'panda.png', 'receipt.png'] for f in all_files: file = open(f, 'w+') file.close() os.mkdir("dir1") os.mkdir("dir2") print(os.listdir())

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

['dir1', 'dir2', 'IMDB Dataset.csv', 'invoice.txt', 'movie_dataset.csv', 'panda.png', 'receipt.png']

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.

import os os.chdir(r"C:\main directory") [os.remove(f) for f in os.listdir() if os.path.isfile(f)] print(os.listdir())

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.

Читайте также:  Установка php iis windows server 2016

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

import os os.chdir(r"C:\main directory") [os.rmdir(f) for f in os.listdir()] print(os.listdir())

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.

from pathlib import Path path = Path(r"C:\main directory") path_list = path.glob("*") [f.unlink() for f in path_list if f.is_file()]

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.

from pathlib import Path [f.unlink() for f in Path(r"C:\main directory").glob("*.png") ]

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.

import shutil shutil.rmtree(r"C:\main directory")

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:

import shutil, os shutil.rmtree(r"C:\main directory") os.mkdir(r"C:\main directory") os.listdir(r"C:\main directory")

Get Our Python Developer Kit for Free

Читайте также:  Php время отправки сообщения

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.

About The Python Tutorials Blog

Ryan Wells

The Python Tutorials Blog was created by Ryan Wells, a Nuclear Engineer and professional VBA Developer. After launching his VBA Tutorials Blog in 2015, he designed some VBA Cheat Sheets, which have helped thousands learn to write better macros. He expanded in 2018 with The Python Tutorials Blog to teach people Python in a similar systematic way. Today, wellsr.com reaches over 2 million programmers each year!

Источник

Python Delete File – How to Remove Files and Folders

Kolade Chris

Kolade Chris

Python Delete File – How to Remove Files and Folders

Many programming languages have built-in functionalities for working with files and folders. As a rich programming language with many exciting functionalities built into it, Python is not an exception to that.

Python has the OS and Pathlib modules with which you can create files and folders, edit files and folders, read the content of a file, and delete files and folders.

In this article, I’ll show you how to delete files and folders with the OS module.

What We’ll Cover

How to Delete Files with the OS Module

To delete any file with the OS module, you can use it’s remove() method. You then need to specify the path to the particular file inside the remove() method. But first, you need to bring in the OS module by importing it:

import os os.remove('path-to-file') 

This code removes the file questions.py in the current folder:

import os os.remove('questions.py') 

If the file is inside another folder, you need to specify the full path including the file name, not just the file name:

import os os.remove('folder/filename.extension') 

The code below shows how I removed the file faq.txt inside the textFiles folder:

import os os.remove('textFiles/faq.txt') 

To make things better, you can check if the file exists first before removing it:

import os # Extract the file path to a variable file_path = 'textFiles/faq.txt' #check if the file exists with path.exists() if os.path.exists(file_path): os.remove('textFiles/faq.txt') print('file deleted') else: print("File does not exists") 

You can also use try..except for the same purpose:

import os try: os.remove('textFiles/faq.txt') print('file deleted') except: print("File doesn't exist") 

How to Delete Files with the Pathlib Module

The pathlib module is a module in Python’s standard library that provides you with an object-oriented approach to working with file system paths. You can also use it to work with files.

The pathlib module has an unlink() method you can use to remove a file. You need to get the path to the file with pathlib.Path() , then call the unlink() method on the file path:

import pathlib # get the file path try: file_path = pathlib.Path('textFiles/questions.txt') file_path.unlink() print('file deleted') except: print("File doesn't exist") 

How to Delete Empty Folders with the OS Module

The OS module provides a rmdir() method with which you can delete a folder.

Читайте также:  Passing argument to php script

But the way you delete an empty folder is not the same way you delete a folder with files or subfolders in it. Let’s see how you can delete empty folders first.

Here’s how I deleted an empty client folder:

import os try: os.rmdir('client') print('Folder deleted') except: print("Folder doesn't exist") 

If you attempt to delete a folder that has files or subfolders inside it, you’ll get the Directory not empty error :

import os os.rmdir('textFiles') # OSError: [Errno 66] Directory not empty: 'textFiles' 

How to Delete Empty Folders with the Pathlib Module

With the pathlib module, you can extract the path of the folder you want to delete into a variable and call rmdir() on that variable:

import pathlib # get the folder path try: folder_path = pathlib.Path('docs') folder_path.rmdir() print('Folder deleted') except: print("Folder doesn't exist") 

To delete a folder that has subfolders and files in it, you have to delete all the files first, then call os.rmdir() or path.rmdir() on the now empty folder. But instead of doing that, you can use the shutil module. I will show you this soon.

How to Delete a Non-Empty with the shutil Module

The shutil module has a rmtree() method you can use to remove a folder and its content – even if it contains multiple files and subfolders.

The first thing you need to do is to extract the path to the folder into a variable, then call rmtree() on that variable.

Here’s how I deleted a folder named subTexts inside the textFiles folder:

import shutil try: folder_path = 'textFiles/subTexts' shutil.rmtree(folder_path) print('Folder and its content removed') except: print('Folder not deleted') 

And here’s how I removed the whole textFiles folder (it has several files and a subfolder):

import shutil try: folder_path = 'textFiles' shutil.rmtree(folder_path) print('Folder and its content removed') # Folder and its content removed except: print('Folder not deleted') 

Conclusion

This article took you through how to remove a file and empty folder with the os and pathlib modules of Python. Because you might also need to remove non-empty folders too, we took a look at how you can do it with the shutil module.

If you found the article helpful, don’t hesitate to share it with your friends and family.

Kolade Chris

Kolade Chris

Web developer and technical writer focusing on frontend technologies. I also dabble in a lot of other technologies.

If you read this far, tweet to the author to show them you care. Tweet a thanks

Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

freeCodeCamp is a donor-supported tax-exempt 501(c)(3) charity organization (United States Federal Tax Identification Number: 82-0779546)

Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.

Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.

Источник

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