Python Current Working Directory

Kailash Chandra Behera | Thursday, May 26, 2022

Introduction

If you are a programmer, you must have come across a requirement where in you need to access directory or folder. Here in this article, we will learn how to interact with python working directory like access python current working directory or python current directory, set and print working directory.

Getting Started

The python current working directory is the folder where your python application is running from. When dealing with files in Python, it is always a good idea to use absolute paths. There are two types of paths in Python concept that is Absolute Paths and Relative Paths.

An absolute path is a path that contains the entire path to the file or directory that you need to access. A relative path is the path that is relative to the working directory location of your application.

However, if you are working with relative paths, you’ll need to understand the concept of the current working directory and how to find or change the current working directory.

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.

In the below we will first see how will access the working directory

Python Get Current Directory

Here below are the code examples for the various ways to access the python current working directory,

  1. Using OS lib
     import os  
     w_dir = os.getcwd()  
     print(w_dir)#python print working directory  
    
  2. Using pathlib
     from pathlib import Path  
     work_dir = Path.cwd()  
     print(work_dir)  
    
  3. Using os path function
     import os  
     print(os.path.dirname(os.path.normpath(__file__)))  
    

    Here in the above code the __file__ is a special Python built in variable that contains the path to the currently running script. The os.path.dirname returns the directory name of the given path and the normpath method normalizes a path name by collapsing redundant separators.

Python Set Working Directory

Here in the below, the code example shows how to change python working directory.

 import os  
 print("Current working directory: {0}".format(os.getcwd()))  
 os.chdir('/tmp')  
 print("Current working directory: {0}".format(os.getcwd()))  

Summary

Here above, we learned that how to access the python current directory( using pythong pwd ) and also we learned change current and print the current directory in Pythong. I hope this article is helpful to you.

Thanks


No comments: