Ben Soyka
Ben Soyka

Reputation: 884

Is there an easy way in Python to get a file by name without knowing the extension?

I have a subdirectory set up such that there will be many different image files, each with a different name and a few possible extensions.

For example, let's say my directory is laid out like this:

.
├── img/
│   ├── bar.gif
│   ├── baz.jpg
│   ├── foo.png
│   └── foobar.png
└── main.py

(There won't be situations like foo.png and foo.gif both existing. Also, the only file extensions being used will be .png, .gif, and .jpg/.jpeg.)

In this example, I would like to be able to open foobar.jpg just by knowing the name foobar.

Is this possible with Python? Is there a PyPI module I might need to use? Thank you!

Upvotes: 0

Views: 447

Answers (1)

Grismar
Grismar

Reputation: 31319

Given the file structure given in the example in the question:

from pathlib import Path

names = ['bar', 'baz', 'foo', 'foobar']

for name in names:
    for fn in Path('img').glob(f'{name}.*'):
        print(f'Found {fn}')

Should give you the output:

Found img\bar.gif
Found img\baz.jpg
Found img\foo.png
Found img\foobar.png

Upvotes: 2

Related Questions