-2

For a project I am working on in python, I need to be able to view what directory a file is in. Essentially it is a find function, however I have no idea how to do this using python.

I have tried searching on google, but only found how to view files inside a directory. I want to view directory using a file name.

To summarise: I don't know the directory, and want to find it using the file inside it.

Thanks.

2 Answers2

0

Here's what I did:

import os
print(os.getcwd())
Kimvais
  • 38,306
  • 16
  • 108
  • 142
0

In Python, the common standard libraries for working with your local files are:

  • os.path
  • os
  • pathlib

If you have a path to a file & want it's directory, then we need to extract it:

>>> import os
>>> filepath = '/Users/guest/Desktop/blogpost.md'
>>> os.path.dirname(filepath) # Returns a string of the directory name
'/Users/guest/Desktop'

If you want the directory of your script, the keyword you need to search for is the "current working directory":

>>> import os
>>> os.getcwd() # returns a string of the current working directory
'/Users/guest/Desktop'

Also check out this SO post for more common operations you'll likely need.