【问题标题】:python find file and change directory to file pathpython查找文件并将目录更改为文件路径
【发布时间】:2014-01-11 21:44:46
【问题描述】:

我想使用 os.walk 搜索 cwd 和子目录以找到特定文件,并在找到时立即中断并更改到该目录。我见过很多在定位文件后中断的例子,但我不知道如何检索路径位置以便更改目录。

【问题讨论】:

    标签: python os.walk chdir


    【解决方案1】:

    这样的?

    f = 'filename'
    for path, dirs, files in os.walk('.'):
        if f in files:
            os.chdir(path)
            break
    

    【讨论】:

    • 就是这样。简单纯粹的简洁。
    【解决方案2】:
    import os
    
    required_file = "somefile.txt"
    cwd = '.'
    
    def get_dir_name(cwd, required_file):
      for dirName, subdirList, fileList in os.walk(cwd):
        for fname in fileList:
            if fname == required_file:
                change_to_dir = os.path.abspath(dirName)
                return change_to_dir
    
    change_to_dir = get_dir_name(cwd, required_file)
    os.chdir(change_to_dir)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-14
      • 1970-01-01
      相关资源
      最近更新 更多