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

2024-07-03 05:47:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Mac上用Pycharm。{{cdm>调用下面的cdm>}函数。它输出“文件存在”,因为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")

Tags: 文件path函数py脚本osmacusers
3条回答

这可能对您有用:

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

试试这个

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

取自:https://stackoverflow.com/a/31621120/5135450

您可以为此使用^{} 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是否为文件的简化版本:

^{pr2}$

理论上,它现在可能是一个目录。在

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

相关问题 更多 >