问题
What's the best way in Python to recursively go through all directories until you find a certain file? I want to look through all the files in my directory and see if the file I'm looking for is in that directory. If I cannot find it, I go to the parent directory and repeat the process. I also want to count how many directories and files I go through before I find the file. If there is no file at the end of the loop return that there is no file
startdir = "Users/..../file.txt"
findfile is name of file. This is my current loop but I want to make it work using recursion.
def walkfs(startdir, findfile):
curdir = startdir
dircnt = 0
filecnt = 0
for directory in startdir:
for file in directory:
curdir = file
if os.path.join(file)==findfile:
return (dircnt, filecnt, curdir)
else:
dircnt+=1
filecnt+=1
回答1:
Don't re-invent the directory-recursion wheel. Just use the os.walk() function, which gives you a loop over a recursive traversal of directories:
def walkfs(startdir, findfile):
dircount = 0
filecount = 0
for root, dirs, files in os.walk(startdir):
if findfile in files:
return dircount, filecount + files.index(findfile), os.path.join(root, findfile)
dircount += 1
filecount += len(files)
# nothing found, return None instead of a full path for the file
return dircount, filecount, None
回答2:
def findPath(startDir,targetFile):
file_count = 0
for i,(current_dir,dirs,files) in enumerate(os.walk(startDir)):
file_count += len(files)
if targetFile in files:
return (i,file_count,os.path.join(current_dir,targetFile))
return (i,file_count,None)
print findPath("C:\\Users\\UserName","some.txt")
来源:https://stackoverflow.com/questions/39879638/recursively-go-through-all-directories-until-you-find-a-certain-file-in-python