Python 3: 在子目录中搜索文件

Python 3: search subdirectories for a file

我在 Mac 上使用 Pycharm。在下面的脚本中,我在名为 dwnld.py 的文件上调用 os.path.isfile 函数。它打印出 "File exists",因为 dwnld.py 与脚本 (/Users/BobSpanks/PycharmProjects/my scripts) 位于同一目录中。 如果我要将 dwnld.py 放在不同的位置,如何让下面的代码在所有从 /Users/BobbySpanks 开始的子目录中搜索 dwnld.py?我尝试阅读 os.path 笔记,但我无法真正找到我需要的东西。我是 Python 的新手。

import os.path

File = "dwnld.py"

if os.path.isfile(File):
    print("File exists")
else:
    print("File doesn't exist")

试试这个

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")

取自:

像这样,使用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 

这可能对你有用:

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

您可以为此使用 glob module

import glob
import os

pattern = '/Users/BobbySpanks/**/dwnld.py'

for fname in glob.glob(pattern, recursive=True):
    if os.path.isfile(fname):
        print(fname)

没有检查 dwnld.py 是否真的是文件的简化版本:

for fname in glob.glob(pattern, recursive=True):
    print(fname)

理论上,现在可以是目录了。

If recursive is true, the pattern '**' will match any files and zero or more directories and subdirectories.