Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting files which start with a name Python

Tags:

python

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

like image 843
chrisg Avatar asked Jan 06 '10 11:01

chrisg


People also ask

How do I remove a file with the name '- something?

How do I remove or access a file with the name '-something' or containing another strange character ? If your file starts with a minus, use the -- flag to rm; if your file is named -g, then your rm command would look like rm -- -g.

How do you delete a file with a wildcard in Python?

Python Delete Files Wildcard To remove files by matching a wildcard pattern such as '*. dat' , first obtain a list of all file paths that match it using glob. glob(pattern) . Then iterate over each of the filenames in the list and remove the file individually using os.

How do you delete a pattern in Python?

To remove files by matching pattern, we need to get list of all files paths that matches the specified pattern using glob. glob() and then delete them one by one using os. remove() i.e.


5 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.

like image 187
Tim Pietzcker Avatar answered Oct 29 '22 06:10

Tim Pietzcker


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.

like image 24
Edan Maor Avatar answered Oct 29 '22 04:10

Edan Maor


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);
like image 23
ternaryOperator Avatar answered Oct 29 '22 04:10

ternaryOperator


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
like image 23
ghostdog74 Avatar answered Oct 29 '22 05:10

ghostdog74


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))
like image 39
cardamom Avatar answered Oct 29 '22 05:10

cardamom