Here I am making attempts to create a code what would delete files in a folder according to the mask. All files what include 17 should be removed File name format is ??_????17*.*, where ? - Any symbol 1..n,A..z, _ and 17 - are in any files (others contain 18, as well) and its extension doesn't matter. Certain example of a file AB_DEFG17Something.Anything - Copy (2).txt
import os
import re
dir_name = "/Python/Test_folder" # open the folder and read files
testfolder = os.listdir(dir_name)
def matching(r, s): # condition if there's nothing to match
match = re.search(r, s)
if match:
return match.group()
return "Files don't exist!"
matching(r'^\w\w\[_]\w\w\w\w\[1]\[7]\w+\[.]\w+', testfolder) # matching the file's mask
for item in testfolder.index(matching):
if item.name(matching, s):
os.remove(os.path.join(dir_name, item))
# format of filenames not converted : ??_????17*.*
# convert for python separarately : [\w][\w][_\w][\w][\w][\w]\[1]\[7][\w]+[\.][\w]+
# ? - Any symbol 1..n,A..z \w repeating is *
# * - Any number of symbols 1..n, A..z
# _ and 17 - in any files `
There are a few mistakes, as well.
File "D:\Python\Test_folder\Remover v2.py", line 14, in matching(r'\w\w[_]\w\w\w\w[1][7]\w+[.]\w+', testfolder) # matching the file's mask  File "D:\Python\Test_folder\Remover v2.py", line 9, in matching match = re.search(r, s) File "c:\Program Files (x86)\Wing IDE Personal 6.0\bin\runtime-python2.7\Lib\re.py", line 146, in search return _compile(pattern, flags).search(string)
I'm a beginner and with amateurish approach would like to get experience in PY, parallel learning details. What am I doing wrong? Any help would be useful. Thx
Don't reinvent the wheel, rather use glob()
instead:
import os
from glob import glob
for file in glob('/Python/Test_folder/AB_CDEF17*.*'):
os.remove(file)
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