I have a set of files in folder my_dir
, which is not the folder where my Python script resides. Sample content of my_dir
:
foo.bar ba.bar moog_0001.h5 moog_0007.h5 moog_0020.h5 moog_0027.h5 moog_0032.h5 moog_0039.h5 moog_0041.h5 moog_0053.h5 moog_0060.h5
I need to:
- find the files with extension
.h5
- for each such file, extract the 4 digits in the filename which follow the underscore
_
. Note: if a file has the extension.h5
, its filename always contains a substring_dddd
. There can be other digit groups in the full pathname of the file, but none starts with a_
, followed by 4 digits, and ends with a.
- if the resulting integer is not divisble by 20, delete the corresponding file
According to these rules, after running the script the content of the folder my_dir
must be:
foo.bar ba.bar moog_0020.h5 moog_0060.h5
My solution:
import os
import re
MY_DIR = "/tmp/logs/20190519T1032"
root, dirs, files = next(os.walk(MY_DIR, topdown=True))
files = [ os.path.join(root, f) for f in files ]
print(files)
files = [ file for file in files if file.endswith(".h5") ]
for file in files:
match = re.search(r'_\d{4}', file).group(0)
match = match[1:]
digits = int(match)
if digits % 20 != 0:
print("remove file " + file )
os.remove(file)
else:
print("skip file " + file)
Any suggestions? I was told to put the content of the for
block in a function, in order to substitute the for
block with a list comprehension, but I don't know if it would be significantly faster (the number of files is O(103), tops). Also, the resulting function wouldn't do only one thing: at the very least, it would extract the 4 digits and delete those files for which the corresponding integer is not divisible by 20. I think that most functions should only one thing.