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 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab