3

I Have a Question : I need to get paths of a file in a directory, I have a folder that contains other folders and other folders etc.... and each of them contains a file "tv.sas7bdat" I need to get every path to that file. Thank you !!!

locke14
  • 1,335
  • 3
  • 15
  • 36
Shahine Greene
  • 196
  • 1
  • 3
  • 15

5 Answers5

3

You can try the following code, where PATH stands for the parent directory

import os
def getAlldirInDiGui(path,resultList):
    filesList=os.listdir(path)
    for fileName in filesList:
        fileAbpath=os.path.join(path,fileName)
        if os.path.isdir(fileAbpath):
            getAlldirInDiGui(fileAbpath,resultList)
        else:
            if fileName=='tv.sas7bdat':
                resultList.append(fileAbpath)
resultList = []
PATH = ""
getAlldirInDiGui(PATH,resultList)
wangtianye
  • 306
  • 1
  • 5
2

If I get your problem right you can achieve your goal using Pythons's os.walk function, like so:

import os
for root, dirs, files in os.walk("<starting folder here>", topdown=False):
    for name in files:
        if name == "tv.sas7bdat":
            print(os.path.join(root, name))

p.s: as for comments in your question, next time please provide as many details possible in your question and provide code of your attempt, see the asking guidelines

Hrabal
  • 2,403
  • 2
  • 20
  • 30
2

You can use os.walk()

import os

for root, dirs, files in os.walk(os.getcwd()):
    for f in files:
        if f.find("tv.sas7bdat")>=0:
            print(root,f)
Vinu Chandran
  • 305
  • 2
  • 10
1

Hope fully below code should work for you:

import glob
initial_path = "c:\<intital folder location>"
files = [file for file in glob.glob(initial_path+ "tv.sas7bdat" , recursive=True)]
for f in files:
    print(f)
rocky
  • 139
  • 3
  • 16
1

You could use the os python package combined with a recursive function to search through a certain directory

import os
from os.path import isfile, join, isdir

def get_files_path(directory, paths):
    for item in os.listdir(directory):
        if isfile(join(directory, item)) and item == "tv.sas7bda":
            paths.append(directory + item)
        elif isdir(directory+item):
            get_files_path(directory + item, paths)
    return paths

directory_to_search = "./"
get_files_path(directory_to_search , [])
vlemaistre
  • 3,301
  • 13
  • 30