Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the current directory and file's directory [duplicate]

In Python, what commands can I use to find:

  1. the current directory (where I was in the terminal when I ran the Python script), and
  2. where the file I am executing is?
like image 425
John Howard Avatar asked Feb 28 '11 01:02

John Howard


People also ask

How do I get the current directory in Python?

To find the current working directory in Python, use os. getcwd() , and to change the current working directory, use os. chdir(path) .

How do I find my current working directory in R?

If we want to check the current directory of the R script, we can use getwd( ) function. For getwd( ), no need to pass any parameters. If we run this function we will get the current working directory or current path of the R script. To change the current working directory we need to use a function called setwd( ).

How do I get the current working directory in Linux?

To print the current working directory, we use the pwd command in the Linux system. pwd (print working directory) – The pwd command is used to display the name of the current working directory in the Linux system using the terminal.


2 Answers

To get the full path to the directory a Python file is contained in, write this in that file:

import os  dir_path = os.path.dirname(os.path.realpath(__file__)) 

(Note that the incantation above won't work if you've already used os.chdir() to change your current working directory, since the value of the __file__ constant is relative to the current working directory and is not changed by an os.chdir() call.)


To get the current working directory use

import os cwd = os.getcwd() 

Documentation references for the modules, constants and functions used above:

  • The os and os.path modules.
  • The __file__ constant
  • os.path.realpath(path) (returns "the canonical path of the specified filename, eliminating any symbolic links encountered in the path")
  • os.path.dirname(path) (returns "the directory name of pathname path")
  • os.getcwd() (returns "a string representing the current working directory")
  • os.chdir(path) ("change the current working directory to path")
like image 144
Russell Dias Avatar answered Sep 20 '22 14:09

Russell Dias


Current working directory: os.getcwd()

And the __file__ attribute can help you find out where the file you are executing is located. This Stack Overflow post explains everything: How do I get the path of the current executed file in Python?

like image 31
Nix Avatar answered Sep 23 '22 14:09

Nix