How does one get all files in a directory with a specific pattern in their names in Python

StackOverflow https://stackoverflow.com/questions/16537708

  •  29-05-2022
  •  | 
  •  

Question

I need to get all filenames from a directory with a specific ending. The files i want from the directory have the same name but with different numbers, other files exist in the same directory. All the files are numbered in the following format:

Project_Name_1.txt
Project_Name_2.txt
Project_Name_3.txt
Project_Name_14.txt
Project_Name_19.txt
Project_Name_31.txt 

The number of files can vary. And The file names (apart from the numbering) are user dependent. I'm looking for something like the following:

[s for s in os.listdir(directory) if "*_*.txt" in s ]

or

glob.glob(directory, '*_?.txt')
Was it helpful?

Solution

How about

name = 'Project_Name'
glob.glob(os.path.join(directory, '{}_*.txt'.format(name)))

this lets files like "Project_Name_SOMETHING.txt" through, so you want to check them afterwards.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top