Deleting files which start with a name Python

Viewed 39854

I have a few files I want to delete, they have the same name at the start but have different version numbers. Does anyone know how to delete files using the start of their name?

Eg.
version_1.1
version_1.2

Is there a way of delting any file that starts with the name version?

Thanks

6 Answers
import os, glob
for filename in glob.glob("mypath/version*"):
    os.remove(filename) 

Substitute the correct path (or . (= current directory)) for mypath. And make sure you don't get the path wrong :)

This will raise an Exception if a file is currently in use.

If you really want to use Python, you can just use a combination of os.listdir(), which returns a listing of all the files in a certain directory, and os.remove().

I.e.:

my_dir = # enter the dir name
for fname in os.listdir(my_dir):
    if fname.startswith("version"):
        os.remove(os.path.join(my_dir, fname))

However, as other answers pointed out, you really don't have to use Python for this, the shell probably natively supports such an operation.

In which language?

In bash (Linux / Unix) you could use:

rm version*

or in batch (Windows / DOS) you could use:

del version*

If you want to write something to do this in Python it would be fairly easy - just look at the documentation for regular expressions.

edit: just for reference, this is how to do it in Perl:

opendir (folder, "./") || die ("Cannot open directory!");
@files = readdir (folder);
closedir (folder);

unlink foreach (grep /^version/, @files);
import os
os.chdir("/home/path")
for file in os.listdir("."):
    if os.path.isfile(file) and file.startswith("version"):
         try:
              os.remove(file)
         except Exception,e:
              print e

The following function will remove all files and folders in a directory which start with a common string:

import os
import shutil

def cleanse_folder(directory, prefix):
    for item in os.listdir(directory):
        path = os.path.join(directory, item)
        if item.startswith(prefix):
            if os.path.isfile(path):
                os.remove(path)
            elif os.path.isdir(os.path.join(directory, item)):
                shutil.rmtree(path)
            else:
                print("A simlink or something called {} was not deleted.".format(item))
import os
import re
directory = "./uploaded"
pattern = "1638813371180"
files_in_directory = os.listdir(directory)
filtered_files = [file for file in files_in_directory if ( re.search(pattern,file))]
for file in filtered_files:
    path_to_file = os.path.join(directory, file)
    os.remove(path_to_file)
Related