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. 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.
Asked
Active
Viewed 1,006 times
2 Answers
4
Something like this?
f = 'filename'
for path, dirs, files in os.walk('.'):
if f in files:
os.chdir(path)
break

Paulo Bu
- 29,294
- 6
- 74
- 73
-
That was it. Simple pure concise. – Gary Washington Jan 12 '14 at 07:32
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)

praveen
- 3,193
- 2
- 26
- 30