Dhruv Pahuja
Dhruv Pahuja

Reputation: 135

How to open a file through python with folder name a regular expression?

I want to open a file ex: xyz.txt which is in a folder named ex: abc_4564536_01_r4897934. Now let suppose I only know that folder name consist of "4564536_01" and there is no other folder with the same string in its name.

Upvotes: 0

Views: 102

Answers (1)

Robᵩ
Robᵩ

Reputation: 168706

Your post title asks for a solution involving regular expressions, but glob is probably a better choice.

glob.glob() returns a list of filenames that match a certain pattern.

import glob

fname = glob.glob("*4564536_01*/xyz.txt")[0]
with open(fname) as fp:
    print fp.read()

Upvotes: 1

Related Questions