Removing Files Starting With a Python Name

I have several files that I want to delete, they have the same name at the beginning, 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 to divide any file that starts with a version of the name?

thanks

+5
source share
4 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 are not mistaken :)

This will throw an exception if the file is currently in use.

+13
source

Python, os.listdir(), os.remove().

:.

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))

, , Python , , , ​​.

+4

?

bash (Linux/Unix) :

rm version*

(Windows/DOS), :

del version*

- Python, - .

: , Perl:

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

unlink foreach (grep /^version/, @files);
+3
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
+1

All Articles