For starter, you could organize your code into functions and use the if __name__ == '__main__'
guard.
You could also change the construct for
loop + if fnmatch.fnmatch
into for … in fnmatch.filter()
.
This would yield something like:
import os
import fnmatch
def filter_files(path='~/Desktop', filter_pattern='*.jpg'):
for root, _, filenames in os.walk(os.path.expanduser(path)):
for filename in fnmatch.filter(filenames, filter_pattern):
yield os.path.join(root, filename)
def write_to_file(iterable, filename='files/list.txt'):
with open(filename, 'w') as output:
for element in iterable:
output.write(element)
output.write('\n')
if __name__ == '__main__':
pictures = filter_files('~/Desktop/photos')
write_to_file(pictures)
However, this code can be greatly improved if you switch to using Python 3.5+ as the recursive filtering is exactly implemented in glob.glob
:
import glob
def write_to_file(iterable, filename='files/list.txt'):
with open(filename, 'w') as output:
for element in iterable:
output.write(element)
output.write('\n')
if __name__ == '__main__':
pattern = 'C:\\Users\\Agartha\\Desktop\\photos\\**\\*.jpg'
pictures = glob.iglob(pattern, recursive=True)
write_to_file(pictures)
You could still maintain the filter_files
function for easier interface:
import glob
from os.path import expanduser, join as path_join
def filter_files(path='~/Desktop', filter_pattern='*.jpg'):
pattern = path_join(expanduser(path), '**', filter_pattern)
yield from glob.iglob(pattern, recursive=True)
def write_to_file(iterable, filename='files/list.txt'):
with open(filename, 'w') as output:
for element in iterable:
output.write(element)
output.write('\n')
if __name__ == '__main__':
pictures = filter_files('~/Desktop/photos')
write_to_file(pictures)
os.path.join
on a single argument? Did you meant to writeos.path.join(path, filename)
? \$\endgroup\$fnmatch
actually convert the pattern to a regex under the hood. See the source code, \$\endgroup\$