Since your question is about picking the best style, it's somewhat opinion-based - which is dangerous territory for StackOverflow, but I think there's something to be said for following the conventions of the most current version of the language:
from pathlib import Path
# input_dir and output_dir are defined somewhere
input_dir = '.'
output_dir = 'c:/temp'
# the 'improved' code
for input_file in Path(input_dir).glob('**/*'):
if input_file.is_file() and input_file.suffix.lower() == '.png':
output_file = Path(output_dir) / input_file.parent.name / input_file.name
# do something with input_file and output_file
print(input_file, output_file)
For pure performance, your original solution may be a bit faster, but I think this beats it for readability and robustness.
Note that I also added a .lower()
to the suffix check, as you would be missing files that have '.PNG'
for an extension.
As @Pepsi-Joe correctly pointed out, if you are really only after .png
files, this is an optimisation that could be considered even cleaner:
for input_file in Path(input_dir).glob('**/*.png'):
if input_file.is_file():
output_file = Path(output_dir) / input_file.parent.name / input_file.name
# do something with input_file and output_file
print(input_file, output_file)
You still need to check for files, as a folder could also be named something.png
of course. .glob()
is case-insensitive, so it will still work for something.PNG
as well.
The previous solution makes it a bit easier to add file formats:
for input_file in Path(input_dir).glob('**/*'):
if input_file.is_file() and input_file.suffix.lower() in ['.png', '.jpg']:
output_file = Path(output_dir) / input_file.parent.name / input_file.name
# do something with input_file and output_file
print(input_file, output_file)