Reputation: 145
I have a directory that looks like the following:
> myDirectory
> L1.zip
> L2_abc.zip
I want to search through the directory to return if a file exists, but I will only have the first part of the zip file name (L1 or L2). How would I go about checking if the file exists?
The results should look a little like the following:
>>> file_exists("L1")
true
>>> file_exists("L2")
true
I am currently just using os.path.exists()
, but I don't know how to ignore the _abc
part of the file name.
Upvotes: 1
Views: 2587
Reputation: 150031
You could use pathlib
:
from pathlib import Path
def file_exists(prefix):
return any(Path("myDirectory").glob(prefix + "*"))
Upvotes: 0
Reputation: 311998
Using glob
, and checking if the result output is empty or not should do the trick:
from glob import glob
def file_exists(filename):
return bool(glob(filename + '.*'))
Upvotes: 2
Reputation: 3464
you can use listdir and do a custom check. Here's one way that only matches if the file/dir starts with L2
matches = [f for f in os.listdir() if f.startswith("L2")]
print(matches)
Upvotes: 3