tags:

views:

78

answers:

4

Hello,

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

+3  A: 

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);
ternaryOperator
+2  A: 
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.

Tim Pietzcker
The exception is only raised on windows. Deleting files work a little different on Unices.
gnud
A: 

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.

Edan Maor
A: 
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
ghostdog74