【发布时间】:2014-01-11 21:44:46
【问题描述】:
我想使用 os.walk 搜索 cwd 和子目录以找到特定文件,并在找到时立即中断并更改到该目录。我见过很多在定位文件后中断的例子,但我不知道如何检索路径位置以便更改目录。
【问题讨论】:
我想使用 os.walk 搜索 cwd 和子目录以找到特定文件,并在找到时立即中断并更改到该目录。我见过很多在定位文件后中断的例子,但我不知道如何检索路径位置以便更改目录。
【问题讨论】:
这样的?
f = 'filename'
for path, dirs, files in os.walk('.'):
if f in files:
os.chdir(path)
break
【讨论】:
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)
【讨论】: