I need to specify multiple file extensions like pathlib.Path(temp_folder).glob('*.xls', '*.txt'):
How I can do it?
https://docs.python.org/dev/library/pathlib.html#pathlib.Path.glob
The pathlib is a Python module which provides an object API for working with files and directories. The pathlib is a standard module. Path is the core object to work with files.
glob (short for global) is used to return all file paths that match a specific pattern. We can use glob to search for a specific file pattern, or perhaps more usefully, search for files where the filename matches a certain pattern by using wildcard characters.
Python glob. glob() method returns a list of files or folders that matches the path specified in the pathname argument. This function takes two arguments, namely pathname, and recursive flag. pathname : Absolute (with full path and the file name) or relative (with UNIX shell-style wildcards).
A bit late to the party with a couple of single-line suggestions that don't require writing a custom function nor the use of a loop and work on Linux:
pathlib.Path.glob() takes interleaved symbols in brackets. For the case of ".txt" and ".xls" suffixes, one could write
files = pathlib.Path('temp_dir').glob('*.[tx][xl][ts]')
If you need to search for ".xlsx" as well, just append the wildcard "*" after the last closing bracket.
files = pathlib.Path('temp_dir').glob('*.[tx][xl][ts]*')
A thing to keep in mind is that the wildcard at the end will be catching not only the "x", but any trailing characters after the last "t" or "s".
Prepending the search pattern with "**/" will do the recursive search as discussed in previous answers.
If you need to use pathlib.Path.glob()
from pathlib import Path
def get_files(extensions):
all_files = []
for ext in extensions:
all_files.extend(Path('.').glob(ext))
return all_files
files = get_files(('*.txt', '*.py', '*.cfg'))
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