MagicforestA 2022-06-25 21:42 采纳率: 100%
浏览 68
已结题

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

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

  • 写回答

3条回答 默认 最新

  • CSDN专家-showbo 2022-06-25 22:32
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 7月5日
  • 已采纳回答 6月27日
  • 修改了问题 6月25日
  • 创建了问题 6月25日

悬赏问题

  • ¥15 python变量和列表之间的相互影响
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)