Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search a folder for files like "/*tmp*.log" in Python

As the title says, I'm using Linux, and the folder could contain more than one file, I want to get the one its name contain *tmp*.log (* means anything of course!). Just like what I do using Linux command line.

like image 565
JustRegisterMe Avatar asked Feb 20 '26 11:02

JustRegisterMe


2 Answers

Use the glob module.

>>> import glob
>>> glob.glob('./[0-9].*')
['./1.gif', './2.txt']
>>> glob.glob('*.gif')
['1.gif', 'card.gif']
>>> glob.glob('?.gif')
['1.gif']
like image 85
Otto Allmendinger Avatar answered Feb 22 '26 00:02

Otto Allmendinger


The glob answer is easier, but for the sake of completeness: You could also use os.listdir and a regular expression check:

import os
import re
dirEntries = os.listdir(path/to/dir)
for entry in dirEntries:
  if re.match(".*tmp.*\.log", entry):
    print entry
like image 45
PTBNL Avatar answered Feb 22 '26 00:02

PTBNL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!