[英]python find file and change directory to file path
I'm wanting to use os.walk to search the cwd and subdirectories to locate a specific file and when found immediately break and change to that dir. 我想使用os.walk搜索cwd和子目录以找到特定的文件,当发现该文件时立即中断并更改为该目录。 I've seen many examples where it breaks after locating the file, but I can't figure out how to retrieve the path location so I can change dir.
我已经看过许多示例,在找到文件后它会中断,但是我不知道如何检索路径位置,因此可以更改dir。
Something like this? 像这样吗
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.