1

Suppose there is a directory somewhere in my computer (I don't know its path) and I don't want to search it by myself rather I want my script to find it out by itself using the 'directory name' (provided no ambiguity) and if it exists then how can I import files from that into the script.

Any help is appreciated.

FlyingTeller
  • 17,638
  • 3
  • 38
  • 53
  • 2
    Take a look at `os.walk()` and `importlib` – match Feb 20 '19 at 14:54
  • Sounds a bit like this could be an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Care to elaborate what your questions background is? – FlyingTeller Feb 20 '19 at 14:55
  • Sure. so I have a script from which I have to run a batch file and this batch file is in another directory in my computer (I know where it is but I want the script to find it by 'dir name') and once it finds that directory exists I want to import the batch file into the script from which I want to run it. Any suggestions. – the bipolar bear Feb 20 '19 at 14:59
  • Possible duplicate of [Find a file in python](https://stackoverflow.com/questions/1724693/find-a-file-in-python) ... Searching for directory/path name is essentially the same as searching for a file name. – wwii Feb 20 '19 at 15:22

1 Answers1

0
import fnmatch
import os

dir_name = 'untitled'
matches = []

for root, dirnames, filenames in os.walk("C:/"):
    for filename in fnmatch.filter(dirnames, dir_name):
         matches.append(os.path.join(root, filename))

print (matches)

result:

['C:/Users\user\Desktop\untitled']

ncica
  • 7,015
  • 1
  • 15
  • 37