+1 vote
1 view
in Python by (2.6k points)
edited by

In Python What command can I use to find these:

  •     Location of file which I am executing, and
  •     Current directory (where I was in the terminal at the time I ran the script in Python)

2 Answers

0 votes
by (10.9k points)
edited by

To get the path to the directory where the Python file is stored write the code below in that file:

import os 

directory_path = os.path.dirname(os.path.realpath(__file__))

The above code may fail if you have already used os.chdir() to change the working of your current directory because the value of _file_ constant is relative with the current working directory and does not change by an os.chdir() call.

If you want to get the current working directory use the following code:

import os

cw_d = os.getcwd()

Here, os.getcwd() returns a string representing the current working directory. 

Hope it helps!

0 votes
by (107k points)

By using the below-mentioned code you  can find the current directory in Python:-

import os

print("Path at terminal when executing this file")

print(os.getcwd() + "\n")

print("This file path, relative to os.getcwd()")

print(__file__ + "\n")

print("This file full path (following symlinks)")

full_path = os.path.realpath(__file__)

print(full_path + "\n")

print("This file directory and name")

path, filename = os.path.split(full_path)

print(path + ' --> ' + filename + "\n")

print("This file directory only")

print(os.path.dirname(full_path))

You can use the following video tutorials to clear all your doubts:-

Related questions

0 votes
1 answer
+3 votes
2 answers
+1 vote
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...