Python: search for a file in current directory and all it's parents -
is there inbuilt module search file in current directory, super-directories?
without module, i'll have list files in current directory, search file in question, , recursively move if file isn't present. there easier way this?
well not implemented, work
use listdir
list of files/folders in current directory , in list search file.
if exists loop breaks if doesn't goes parent directory using os.path.dirname
, listdir
.
if cur_dir == '/'
parent dir "/"
returned "/"
if cur_dir == parent_dir
breaks loop
import os file_name = "test.txt" #file searched cur_dir = os.getcwd() # dir search starts can replaced path while true: file_list = os.listdir(cur_dir) parent_dir = os.path.dirname(cur_dir) if file_name in file_list: print "file exists in: ", cur_dir break else: if cur_dir == parent_dir: #if dir root dir print "file not found" break else: cur_dir = parent_dir
Comments
Post a Comment