Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python glob multiple filetypes

Tags:

python

glob

Is there a better way to use glob.glob in python to get a list of multiple file types such as .txt, .mdown, and .markdown? Right now I have something like this:

projectFiles1 = glob.glob( os.path.join(projectDir, '*.txt') ) projectFiles2 = glob.glob( os.path.join(projectDir, '*.mdown') ) projectFiles3 = glob.glob( os.path.join(projectDir, '*.markdown') ) 
like image 519
Raptrex Avatar asked Dec 31 '10 06:12

Raptrex


People also ask

What is glob glob () in Python?

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).

What are glob files?

A glob is a term used to define patterns for matching file and directory names based on wildcards. Globbing is the act of defining one or more glob patterns, and yielding files from either inclusive or exclusive matches.

Is glob built in Python?

With glob, we can also use wildcards ("*, ?, [ranges]) apart from exact string search to make path retrieval more simple and convenient. Note: This module comes built-in with Python, so there is no need to install it externally.


2 Answers

Maybe there is a better way, but how about:

import glob types = ('*.pdf', '*.cpp') # the tuple of file types files_grabbed = [] for files in types:     files_grabbed.extend(glob.glob(files))  # files_grabbed is the list of pdf and cpp files 

Perhaps there is another way, so wait in case someone else comes up with a better answer.

like image 128
user225312 Avatar answered Sep 22 '22 15:09

user225312


glob returns a list: why not just run it multiple times and concatenate the results?

from glob import glob project_files = glob('*.txt') + glob('*.mdown') + glob('*.markdown') 
like image 23
patrick-mooney Avatar answered Sep 24 '22 15:09

patrick-mooney