问题
I'm using Pycharm on a Mac. In the script below I'm calling the os.path.isfile
function on a file called dwnld.py
. It prints out "File exists" since dwnld.py
is in the same directory of the script (/Users/BobSpanks/PycharmProjects/my scripts
).
If I was to put dwnld.py
in a different location, how to make the code below search all subdirectories starting from /Users/BobbySpanks
for dwnld.py
? I tried reading os.path
notes but I couldn't really find what I needed. I'm new to Python.
import os.path
File = "dwnld.py"
if os.path.isfile(File):
print("File exists")
else:
print("File doesn't exist")
回答1:
This might work for you:
import os
File = 'dwnld.py'
for root, dirs, files in os.walk('/Users/BobbySpanks/'):
if File in files:
print ("File exists")
os.walk(top, topdown=True, onerror=None, followlinks=False)
Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames). Source
回答2:
You can use the glob module for this:
import glob
import os
pattern = '/Users/BobbySpanks/**/dwnld.py'
for fname in glob.glob(pattern, recursive=True):
if os.path.isfile(fname):
print(fname)
A simplified version without checking if dwnld.py
is actually file:
for fname in glob.glob(pattern, recursive=True):
print(fname)
Theoretically, it could be a directory now.
If recursive is true, the pattern
'**'
will match any files and zero or more directories and subdirectories.
回答3:
Try this
import os
File = "dwnld.py"
for root, dirs, files in os.walk('.'):
for file in files: # loops through directories and files
if file == File: # compares to your specified conditions
print ("File exists")
Taken from: https://stackoverflow.com/a/31621120/5135450
回答4:
something like this, using os.listdir(dir):
import os
my_dirs = os.listdir(os.getcwd())
for dirs in my_dirs:
if os.path.isdir(dirs):
os.chdir(os.path.join(os.getcwd(), dirs)
#do even more
来源:https://stackoverflow.com/questions/41191864/python-3-search-subdirectories-for-a-file