Python get current directory

Introduction

Today, we are going to talk about directories, files and paths in Python. If you are in rush and only need to know the syntax, here is how to get the current working directory...

# Import os module
import os
# Print current working directory
print(os.getcwd())

For more information, continue reading...

Python provides dedicated cross platform modules to interface with the operating system and file system. In particular, we are going to talk about the os and os.path modules...

  • os module provides a portable interface to work with operating system dependent functionality
  • os.path module is used to manipulate file system paths

Will start with the __file__ constant...

__file__ constant

Contains file name of the currently executing Python script. It depends on how the script was called (ex. python ./test.py) regardless of the location from which it was invoked.

Let us take an example…

  • Open a text file and give it a name (ex. test.py)
  • Add the following code
print(__file__)
  • Run the script as follows...
python ./test.py
  • You should get the following output...
./test.py

As you can see, it printed the Python script name the way it was invoked.

os.path.realpath()

Returns the full path to a directory or file. It eliminates symbolic links in the path. Here is an example...

  • Create two directories dir1 and dir2
mkdir dir1 dir2
  • Create a symbolic link for dir2 inside dir1
cd dir1; ln -s ../dir2 .
  • Open a text file and give it a name (ex. test.py)
  • Copy the following code to the script
import os.path
print(__file__)
print(os.path.realpath(__file__))
  • Save the python script in dir2
  • Go to dir1/dir2 and run the script...
$ pwd
/Users/moh/dir1/dir2
$ ls
test.py
$ python test.py 
test.py
/Users/moh/dir2/test.py

As you can see, the actual path is printed without any symbolic links. It printed

/Users/moh/dir2/test.py

instead of

/Users/moh/dir1/dir2/test.py

os.path.dirname()

Returns the full path to the directory a file or another directory is contained in. If we split the path into a head and tail then os.path.dirname() returns the head. Here is an example...

import os
print(__file__)
print(os.path.dirname(__file__))

The code snippet above should print something like...

/Users/moh/scripts/test.py
/Users/moh/scripts

os.path.basename()

Returns the tail of the path (as opposed to the head in case of os.path.dirname()). Here is an example...

import os.path
print(__file__)
print(os.path.basename(__file__))

The code snippet above should print something like...

/Users/moh/scripts/test.py
test.py

os.chdir() and os.getcwd()

Current working directory is the directory from which a Python script is invoked and not the actual location of the script. As the names indicate, os.chdir() changes the current working directory and os.getcwd() gets the current working directory. Here is an example…

import os
print(os.getcwd())
os.chdir("/users/moh")
print(os.getcwd())

The code snippet above should print something like...

/Users/moh/scripts
/Users/moh

Using pathlib

pathlib is an object oriented Python standard library to handle paths and filenames instead of using plain strings as in os.path. If you do not have it installed, you can do so by running the following command...

sudo easy_install pathlib

Here is an example...

import pathlib

current_dir = pathlib.Path(__file__).parent
current_file = pathlib.Path(__file__)

print(current_dir)
print(current_file)

The code snippet above should print something like...

/Users/moh/scripts
/Users/moh/scripts/test.py

sys.argv[0]

This is a list that holds the list of command line arguments. system.argv also holds the name of the running script, exactly as it was called from the command line. Let us take an example...

import sys
import os
print(sys.argv[0])       

The code snippet above should print something like...

/Users/moh/scripts/test.py

os.path.abspath()

Returns a fully qualified path of the provided path which can be empty, partial or full. There are three cases...

  • Returns current working directory if the input path is empty
  • Returns a fully qualified path if the input path is partial based on the current working directory
  • If the path is already full os.path.abspath returns the provided path
  • Even if the path does not exist, it will return something, see the example

Here is an example...

import os

# Change current working directory to your home
os.chdir('/Users/moh')
# This will print: /Users/moh
print(os.getcwd())

# This will print: /Users/moh
print(os.path.abspath(''))

# This will print: /Users/moh/.ssh
print(os.path.abspath('.ssh'))

# This will print: /Users/moh/.ssh
print(os.path.abspath('/home/moh/.ssh'))

# This will print: /Users/moh/xyz
print(os.path.abspath('.ssh/../xyz/'))

abspath() vs realpath()

Notice that both abspath() and realpath() look similar so what is the difference between the two?

  • os.path.realpath() deferences symbolic links
  • os.path.abspath() removes the dots that refer to current or parent directory from the path

Here is an example...

import os.path

# 1. Go to /Users/moh/temp
# 2. touch A
# 3. ln -s A B
# 4. ls -al
# 5. You should see two files
#    A
#    B -> A

# Go to your home directory
os.chdir('/Users/moh/temp')

# This should print: /Users/moh/temp/B
print(os.path.abspath('B'))
# This should print: /Users/moh/temp/A
print(os.path.realpath('B'))

As you can see, the os.path.abspath() function gives the fully qualified path to B without dereferencing any symboling links while os.path.realpath() gives the actual path to the file.

References

That is all for today, thanks for visiting. Feedback and questions? Use the comments section below.

Search Terms...
Tags:

Leave a Reply