It licks all files under the specified directory and returns only the file path of the file with the desired extension as a generator. You can do this by using ʻos.walk`.
I think it's a frequently used operation, but I immediately forget how to write it, so I'll make it a function for the future as a memo. It can be used with both Python 2 and 3.
import os
def walk_files_with(extension, directory='.'):
"""Generate paths of all files that has specific extension in a directory.
Arguments:
extension -- [str] File extension without dot to find out
directory -- [str] Path to target directory
Return:
filepath -- [str] Path to file found
"""
for root, dirnames, filenames in os.walk(directory):
for filename in filenames:
if filename.lower().endswith('.' + extension):
yield os.path.join(root, filename)
Actually, it is used like this.
for filepath in walk_files_with('csv', './data/'):
print(filepath)
If you have Python 3.4 or above, it may be smarter to use pathlib
.
Recommended Posts