Python, Can I Get A Return True Or False, If A File Type Exists Or Not?
ive read through the path.exists() and path.isdir() questions on here, but none that ive found so far, deal with check if a particular file type exists in a directory or not... may
Solution 1:
You want to use glob
.
import globif glob.glob("/mnt/path/to/shared/folder/*.txt"):
# there are text fileselse:
# No text files
Glob will return a list of files matching the wildcard-accessible path. If there are no files, it will return an empty list. This is really just os.listdir
and fnmatch.filter
together.
If memory is an issue, use glob.iglob
as 200OK suggests in the comments:
import glob
ifnext(glob.iglob("/mnt/path/to/shared/folder/*.txt"), None):
# there are text fileselse:
# No text files
iglob
builds an iterator instead of a list, which is massively more memory-saving.
Solution 2:
If your problem specifically is to find files with particular criteria, consider opening/reading a pipe to the program find.
As in:
find dir1 dir2 dir3 -name "*.txt"
That program has dozens of options for filtering based on the type of file (symlink, etc) and should give you a lot of flexibility that might be easier than writing it yourself with various python libraries.
Post a Comment for "Python, Can I Get A Return True Or False, If A File Type Exists Or Not?"