Python remove files by mask

Python Delete Files Matching Pattern Example

This tutorial will provide example of python delete files matching pattern. it’s simple example of python delete multiple files wildcard. This post will give you simple example of python delete files with wildcard. you will learn python remove files wildcard. Here, Creating a basic example of remove files python wildcard.

In this example, we will use remove() and glob() of «os» library to delete files with wildcard. so let’s see below example and do it.

remove() will remove file on given path.

glob() will give you files path recursively.

You can use these examples with python3 (Python 3) version.

let’s see below simple example with output:

Example 1: Remove Files with «.txt» Extension

I have created following files on files folder and remove files with «.txt» extension :

files/test.txt files/demo.txt files/first.png
import os, glob # Getting All Files List fileList = glob.glob('files/*.txt', recursive=True) # Remove all files one by one for file in fileList: try: os.remove(file) except OSError: print("Error while deleting file") print("Removed all matched files!")
files/test.txt files/demo.txt

Example 1: Remove Files with «copy*.txt» Pattern Matching

I have created following files on files folder and remove files with «copy*.txt» pattern matching :

files/copy-test.txt files/copy-demo.txt files/demo.txt
import os, glob # Getting All Files List fileList = glob.glob('files/copy*.txt', recursive=True) # Remove all files one by one for file in fileList: try: os.remove(file) except OSError: print("Error while deleting file") print("Removed all matched files!")
files/copy-test.txt files/copy-demo.txt

Hardik Savani

I’m a full-stack developer, entrepreneur and owner of Aatman Infotech. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.

We are Recommending you

  • Python Delete Files with Specific Extension Example
  • Python Delete Directory if Exists Example
  • Python Delete File if Exists Example
  • Python Post Request with pem File Example
  • Python Post Request with Json File Example
  • Python Post Request with Basic Authentication Example
  • Python Post Request with Bearer Token Example
  • Python Get File Extension from Filename Example
  • Python Create Zip Archive from Directory Example
  • How to Check if Today is Sunday or not in Python?
  • How to Check if Today is Thursday or not in Python?
  • How to Check if Today is Wednesday or not in Python?
Читайте также:  Java classes and methods listing

Источник

Python3 delete file – Python: How to remove files by matching pattern | wildcards | certain extensions only?

Python- How to remove files by matching pattern, wildcards, certain extensions only

Python find files matching pattern: In this ultimate tutorial, we are going to discuss how to remove files from a directory based on a matching pattern or wildcard, or specific extensions. You will get the information regarding these also, Python Os.Remove Wildcard, Python Delete File Wildcard, Python Remove Files With Wildcard, Python Delete Files With Wildcard, Python Remove Files Wildcard, Python Remove Files Matching Pattern, Delete File Python, Remove File Python, Python Os Delete File, Delete A File Python, Python Remove File Wildcard, Python Delete Files Matching Pattern, Python Remove Directory.

How to delete text files using different techniques?

Python remove all files in directory: Let’s discuss how to delete text files using different techniques, Suppose we have a directory that contains some log files and some text files and we want to delete all .txt files from that directory.

Then, continue your read so that you can successfully learn to remove files by matching patterns or wildcards by the following methods and techniques.

Remove files by pattern using glob.glob() & os.remove()

Python3 delete file: First, we will get a list of all file paths that match the specified patterns using glob.glob() and then delete all text files.

import os import glob # Get a list of all the file paths that ends with .txt from in specified directory fileList = glob.glob('C://Users/HP/Desktop/A plus topper/*.txt') # Iterate over the list of filepaths & remove each file. for filePath in fileList: try: os.remove(filePath) except: print("Error while deleting file : ", filePath)

So you can see that it will remove all ‘.txt’ files in the directory ‘C:\\Users\HP\Desktop\A plus topper\*.txt’. It will remove all text files because we mention” *.txt “.

Get the list of files using glob.glob()

Python os remove file: glob.glob() accepts path name and finds the path of all the files that match the specified pattern. By default recursive parameter is False, which means that it will find files in the main directory, not in a subdirectory.

As we have seen by this approach we can not recursively delete files from subdirectories. For that, we will find another solution,

Recursively Remove files by matching pattern or wildcard

Python delete all files in directory: It will search all the ‘txt’ files including files in subdirectories because we will use ‘C://Users/HP/Desktop/A plus topper/**/*.txt’ ‘ ** ‘ in it.

Then we can iterate over the list and delete each file one by one using os.remove().

import os import glob # get a recursive list of file paths that matches pattern including sub directories fileList = glob.glob('C://Users/HP/Desktop/A plus topper/**/*.txt', recursive=True) # Iterate over the list of filepaths & remove each file. for filePath in fileList: try: os.remove(filePath) except OSError: print("Error while deleting file")

It will delete all the text files from the directory and its sub-directories.

Recursively Remove files by matching pattern or wildcard using os.walk()

Python rm file: In this, we are going to use os.walk(). It generates filename in the given directory by walking over the tree structure in a top-down or bottom-up approach.

Читайте также:  Ubuntu no java home environment variable is defined

os.walk(top, topdown=True, onerror=None, followlinks=False)

It will return a tuple consisting of the main directory, a list of all subdirectories, and a list of all file names in the main directory.

Let’s use this os.walk() to get a list of all files in a given directory that matches a pattern. Then delete those files,

import os import fnmatch # Get a list of all files in directory for rootDir, subdirs, filenames in os.walk('C://HP/Users/Desktop/A plus topper'): # Find the files that matches the given patterm for filename in fnmatch.filter(filenames, '*.txt'): try: os.remove(os.path.join(rootDir, filename)) except OSError: print("Error while deleting file")

It will delete all the text files from the directory and also from its subdirectories.

Now we are going to create a Generic function to delete all the files from a given directory based on a matching pattern and it will also return the names of the files that were not deleted due to some error.

import os import fnmatch ''' Generic function to delete all the files from a given directory based on matching pattern ''' def removeFilesByMatchingPattern(dirPath, pattern): listOfFilesWithError = [] for parentDir, dirnames, filenames in os.walk(dirPath): for filename in fnmatch.filter(filenames, pattern): try: os.remove(os.path.join(parentDir, filename)) except: print("Error while deleting file : ", os.path.join(parentDir, filename)) listOfFilesWithError.append(os.path.join(parentDir, filename)) return listOfFilesWithError listOfErrors = removeFilesByMatchingPattern('/home/varung/Documents/python/logs/', '*.txt') print('Files that can not be deleted : ') for filePath in listOfErrors: print(filePath)

So in the above code, you can see that it will also return file names that can not be deleted.

Analyze these:

  • How To Delete File In Python
  • Python Remove File Wildcard
  • Delete Files Python
  • Python Rm File

Conclusion:

In this article, we have seen how to remove files from a directory based on matching patterns or wildcards, or certain extensions.

Источник

Python: How to remove files by matching pattern | wildcards | certain extensions only?

Python- How to remove files by matching pattern, wildcards, certain extensions only

In this ultimate tutorial, we are going to discuss how to remove files from a directory based on a matching pattern or wildcard, or specific extensions.

How to delete text files using different techniques?

Let’s discuss how to delete text files using different techniques, Suppose we have a directory that contains some log files and some text files and we want to delete all .txt files from that directory.

Then, continue your read so that you can successfully learn to remove files by matching patterns or wildcards by the following methods and techniques.

Remove files by pattern using glob.glob() & os.remove()

First, we will get a list of all file paths that match the specified patterns using glob.glob() and then delete all text files.

import os import glob # Get a list of all the file paths that ends with .txt from in specified directory fileList = glob.glob('C://Users/HP/Desktop/A plus topper/*.txt') # Iterate over the list of filepaths & remove each file. for filePath in fileList: try: os.remove(filePath) except: print("Error while deleting file : ", filePath)

So you can see that it will remove all ‘.txt’ files in the directory ‘C:\\Users\HP\Desktop\A plus topper\*.txt’. It will remove all text files because we mention” *.txt “.

Читайте также:  Что делает eval python

Get the list of files using glob.glob()

glob.glob() accepts path name and finds the path of all the files that match the specified pattern. By default recursive parameter is False, which means that it will find files in the main directory, not in a subdirectory.

As we have seen by this approach we can not recursively delete files from subdirectories. For that, we will find another solution,

Recursively Remove files by matching pattern or wildcard

It will search all the ‘txt’ files including files in subdirectories because we will use ‘C://Users/HP/Desktop/A plus topper/**/*.txt’ ‘ ** ‘ in it.

Then we can iterate over the list and delete each file one by one using os.remove().

import os import glob # get a recursive list of file paths that matches pattern including sub directories fileList = glob.glob('C://Users/HP/Desktop/A plus topper/**/*.txt', recursive=True) # Iterate over the list of filepaths & remove each file. for filePath in fileList: try: os.remove(filePath) except OSError: print("Error while deleting file")

It will delete all the text files from the directory and its sub-directories.

Recursively Remove files by matching pattern or wildcard using os.walk()

In this, we are going to use os.walk(). It generates filename in the given directory by walking over the tree structure in a top-down or bottom-up approach.

os.walk(top, topdown=True, onerror=None, followlinks=False)

It will return a tuple consisting of the main directory, a list of all subdirectories, and a list of all file names in the main directory.

Let’s use this os.walk() to get a list of all files in a given directory that matches a pattern. Then delete those files,

import os import fnmatch # Get a list of all files in directory for rootDir, subdirs, filenames in os.walk('C://HP/Users/Desktop/A plus topper'): # Find the files that matches the given patterm for filename in fnmatch.filter(filenames, '*.txt'): try: os.remove(os.path.join(rootDir, filename)) except OSError: print("Error while deleting file")

It will delete all the text files from the directory and also from its subdirectories.

Now we are going to create a Generic function to delete all the files from a given directory based on a matching pattern and it will also return the names of the files that were not deleted due to some error.

import os import fnmatch ''' Generic function to delete all the files from a given directory based on matching pattern ''' def removeFilesByMatchingPattern(dirPath, pattern): listOfFilesWithError = [] for parentDir, dirnames, filenames in os.walk(dirPath): for filename in fnmatch.filter(filenames, pattern): try: os.remove(os.path.join(parentDir, filename)) except: print("Error while deleting file : ", os.path.join(parentDir, filename)) listOfFilesWithError.append(os.path.join(parentDir, filename)) return listOfFilesWithError listOfErrors = removeFilesByMatchingPattern('/home/varung/Documents/python/logs/', '*.txt') print('Files that can not be deleted : ') for filePath in listOfErrors: print(filePath)

So in the above code, you can see that it will also return file names that can not be deleted.

Conclusion:

In this article, we have seen how to remove files from a directory based on matching patterns or wildcards, or certain extensions.

Источник

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