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.
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)
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 + '.*'))
You could use pathlib
:
from pathlib import Path
def file_exists(prefix):
return any(Path("myDirectory").glob(prefix + "*"))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.