Vito Gentile
Vito Gentile

Reputation: 14426

Interpret path with * in Windows with Python

I am trying to find the full real path on Windows, based on a path with the * character in it (which seems to be something similar to a regular expression).

For instance, if in a Windows console I do:

cd C:\\Windows\\Program Files\\MySWv1*\\bin

the above path is expanded in something like:

C:\\Windows\\Program Files\\MySWv1.90\\bin

and then the cd command is executed successfully.

However, if in Python (2.7) I try to execute the following:

import os
my_path = 'C:\\Windows\\Program Files\\MySWv1*\\bin'
os.path.exists(my_path)

This returns False.

How can I make the above script returns True?

Upvotes: 4

Views: 215

Answers (1)

Vito Gentile
Vito Gentile

Reputation: 14426

I found the solution here. It is based on the glob module:

import os
import glob
my_path = glob.glob('C:\\Windows\\Program Files\\MySWv1*\\bin')[0]
os.path.exists(my_path)

Actually, glob.glob interprets the path and substitutes any wildcards (like *) with one or more strings, resulting in a list of paths that match them.

This means that, in production code, you should always take into account the possibility that more than one path is produced by glob.glob, and, if needed, do something to manage this rule.

Upvotes: 1

Related Questions