我想使用 os.walk 搜索 cwd 和子目录以找到特定文件,并在找到时立即中断并更改到该目录。我见过很多例子,在找到文件后它会中断,但我不知道如何检索路径位置,所以我可以更改 dir.
问问题
890 次
2 回答
4
像这样的东西?
f = 'filename'
for path, dirs, files in os.walk('.'):
if f in files:
os.chdir(path)
break
于 2014-01-11T21:52:12.303 回答
0
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)
于 2014-01-11T21:56:31.387 回答