PythonOS文件目录方法

img


import os

os.makedirs("./tree/c/other_courses/cpp")
os.makedirs("./tree/c/other_courses/python")
os.makedirs("./tree/cpp/other_courses/c")
os.makedirs("./tree/cpp/other_courses/python")
os.makedirs("./tree/python/other_courses/c")
os.makedirs("./tree/python/other_courses/cpp")
class DirectorySearcher:
    def find(self, path, dir):
        try:
            os.chdir(path)
        except OSError:
            
            return

        current_dir = os.getcwd()
        for entry in os.listdir("."):
            if entry == dir:
                print(os.getcwd() + "/" + dir)
            self.find(current_dir + "/" + entry, dir)


directory_searcher = DirectorySearcher()
directory_searcher.find("./tree", "python")
"""
input:
path="./tree", dir="python"
output:
.../tree/python       #第一条路径
.../tree/cpp/other_courses/python     #2
.../tree/c/other_courses/python         #3
"""

无法显示第二和第三条路径

if entry == dir:
print(os.getcwd()+ "/" + dir)
改为下面的,使用os.getcwd() 得到的是上一次os.chdir(path)进入的目录。第一条路径对比不成功,然后执行递归进入了tree\c\other_courses\cpp,没有子文件夹,执行第二次对比成功,此时os.getcwd()得到的是tree\c\other_courses\cpp这个路径,并不是python所在的目录tree\c\other_courses\,改为current_dir 变量为要匹配的目录所在路径
if entry == dir:
print(current_dir+ "/" + dir)

img


if entry == dir:
                print(os.getcwd() + "/" + dir)
else:

加个else输出一下不满足条件的变量值内容

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632