mehdi_bm
mehdi_bm

Reputation: 409

Find files in a dircetory with special character in its name

I tried to find files in a directory whose name include -, i.e. /0.12345/Name-001-011. Part of the code do it is like this

mypath = '.'
pattern = '\d\.\d*/Name*/NameofFile'
fileList = []

for directory, dirnames, filenames in os.walk(mypath):
   for name in filenames:

     if re.search(pattern,os.path.join(directory,name)):
         fileList.append(os.path.join(directory,name))

but unfortunately it does not find the file, and as I realised the problem stems from having - in the path.

Upvotes: 0

Views: 709

Answers (2)

Agost Biro
Agost Biro

Reputation: 2839

The problem is that there is a missing dot in the regex pattern after Name. The correct pattern is below:

/\d\.\d*/Name.*/NameofFile

As pointed out in the comments, by writing Name* you tell the engine to match 0 or more repetitions of the character e. Instead what you want presumably is to match anything after Name which is achieved by .* where dot stands for any character except newline.

Upvotes: 1

Emma
Emma

Reputation: 27723

I'm guessing that our desired output would be Name-001-011, which this simple expression would capture that:

/[0-9]+\.[0-9]+/(.+)

Demo 1

If we might want to add Name as a boundary and capture the digits, we can try:

/[0-9]+\.[0-9]+/Name-(.+)

or:

/[0-9]+\.[0-9]+/(Name-.+)

or:

/[0-9]+\.[0-9]+/(Name-[0-9]+-[0-9]+)

Demo 2

Upvotes: 1

Related Questions