Logo
  • Ubuntu
  • CentOS
  • Debian
  • Fedora
  • RedHat

How to Get and Change the Current Working Directory in Python - DesignLinux

designlinux 0 Comments

When dealing with files in directories in Python, it is always a good idea to use absolute paths. However, if you are working with relative paths you’ll need to understand the concept of current working directory and how to find or change the current working directory. An absolute path specifies a file or directory location starting from the root directory, while the relative path begins from the current working directory.

When you run a Python script, the current working directory is set to the directory from which the script is executed.

The os python module provides a portable way to interact with the operating system. The module is part of the standard Python library and includes methods for finding and changing the current working directory.

Getting the Current Working Directory in Python #

The getcwd() method of the os module in Python, returns a string that contains the absolute path of the current working directory. The returned string does not include the trailing slash character.

os.getcwd()

To use the os module methods, you must import the module at the top of the file.

Below is an example showing how to print the current working directory:

# Import the os module
import os

# Get the current working directory
cwd = os.getcwd()

# Print the current working directory
print("Current working directory: {0}".format(cwd))

# Print the type of the returned object
print("os.getcwd() returns an object of type: {0}".format(type(cwd)))

The output will look something like this:

Current working directory: /home/linuxize/Desktop
os.getcwd() returns an object of type: <class 'str'>
If you want to find the directory where the script is located, use os.path.realpath(__file__). It will return a string containing the absolute path to the running script.

Changing the Current Working Directory in Python #

To change the current working directory in Python, use the chdir() method.

os.getcwd(path)

The method accepts one argument, the path to the directory to which you want to change. The path argument can be absolute or relative.

Here is an example:

# Import the os module
import os

# Print the current working directory
print("Current working directory: {0}".format(os.getcwd()))

# Change the current working directory
os.chdir('/tmp')

# Print the current working directory
print("Current working directory: {0}".format(os.getcwd()))

The output will look something like this:

Current working directory: /home/linuxize/Desktop
Current working directory: /tmp

The argument provided to the chdir() method must be a directory, otherwise NotADirectoryError exception is raised. If the specified directory doesn’t exist, a FileNotFoundError exception is raised. If the user under which the script is running doesn’t have the necessary permissions, a PermissionError exception is raised.

# Import the os module
import os

path = '/var/www'

try:
    os.chdir(path)
    print("Current working directory: {0}".format(os.getcwd()))
except FileNotFoundError:
    print("Directory: {0} does not exist".format(path))
except NotADirectoryError:
    print("{0} is not a directory".format(path))
except PermissionError:
    print("You do not have permissions to change to {0}".format(path))

Conclusion #

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

If you have any questions or feedback, feel free to leave a comment.

python

Related

Tags: python

Date Command in Linux

Prev Post

Linux Tee Command with Examples

Next Post
Archives
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022
  • July 2022
  • June 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021
  • May 2021
  • April 2021
  • March 2021
  • February 2021
  • January 2021
  • December 2020
  • November 2020
  • October 2020
  • September 2020
  • August 2020
  • July 2020
  • June 2020
  • May 2020
Categories
  • AlmaLinux
  • Android
  • Ansible
  • Apache
  • Arch Linux
  • AWS
  • Backups
  • Bash Shell
  • Bodhi Linux
  • CentOS
  • CentOS Stream
  • Chef
  • Cloud Software
  • CMS
  • Commandline Tools
  • Control Panels
  • CouchDB
  • Data Recovery Tools
  • Databases
  • Debian
  • Deepin Linux
  • Desktops
  • Development Tools
  • Docker
  • Download Managers
  • Drupal
  • Editors
  • Elementary OS
  • Encryption Tools
  • Fedora
  • Firewalls
  • FreeBSD
  • FTP
  • GIMP
  • Git
  • Hadoop
  • HAProxy
  • Java
  • Jenkins
  • Joomla
  • Kali Linux
  • KDE
  • Kubernetes
  • KVM
  • Laravel
  • Let's Encrypt
  • LFCA
  • Linux Certifications
  • Linux Commands
  • Linux Desktop
  • Linux Distros
  • Linux IDE
  • Linux Mint
  • Linux Talks
  • Lubuntu
  • LXC
  • Mail Server
  • Manjaro
  • MariaDB
  • MongoDB
  • Monitoring Tools
  • MySQL
  • Network
  • Networking Commands
  • NFS
  • Nginx
  • Nodejs
  • NTP
  • Open Source
  • OpenSUSE
  • Oracle Linux
  • Package Managers
  • Pentoo
  • PHP
  • Podman
  • Postfix Mail Server
  • PostgreSQL
  • Python
  • Questions
  • RedHat
  • Redis Server
  • Rocky Linux
  • Security
  • Shell Scripting
  • SQLite
  • SSH
  • Storage
  • Suse
  • Terminals
  • Text Editors
  • Top Tools
  • Torrent Clients
  • Tutorial
  • Ubuntu
  • Udemy Courses
  • Uncategorized
  • VirtualBox
  • Virtualization
  • VMware
  • VPN
  • VSCode Editor
  • Web Browsers
  • Web Design
  • Web Hosting
  • Web Servers
  • Webmin
  • Windows
  • Windows Subsystem
  • WordPress
  • Zabbix
  • Zentyal
  • Zorin OS
Visits
  • 0
  • 74
  • 605,824

DesignLinux.com © All rights reserved

Go to mobile version