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
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.
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.
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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With