Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - List Files in a Directory
Next article icon

Get Current directory in Python

Last Updated : 03 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will cover How to Get and Change the Working Directory in Python. While working with file handling you might have noticed that files are referenced only by their names, e.g. ‘GFG.txt’ and if the file is not located in the directory of the script, Python raises an error. The concept of the Current Working Directory (CWD) becomes important here. Consider the CWD as the folder, the Python is operating inside. Whenever the files are called only by their name, Python assumes that it starts in the CWD which means that a name-only reference will be successful only if the file is in Python’s CWD.

Note: The folder where the Python script is running is known as the Current Directory. This may not be the path where the Python script is located.

What is the Python os module?

Python provides an os module for interacting with the operating system. This module comes under Python’s standard utility module. All functions in the os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type but are not accepted by the operating system.

Python Find Current Directory

Get a Directory of the Current Python Script using sys.argv[0]

In this example, we have used sys.argv[0] to retrieve the path of the script file and os.path.dirname() extracts the current directory from the path.

Python3




import os
import sys
script_directory = os.path.dirname(os.path.abspath(sys.argv[0]))
print(script_directory)
 
 

Output :

Get directory of current Python script

Get a directory of the current Python script

Get the Directory of the Current Python Script using Inspect Module 

In this example, we have used inspect.getfile(inspect.currentframe()) which returns the path of the current script file, and os.path.dirname() extracts the current directory from the path.

Python3




import inspect
import os
script_directory = os.path.dirname(os.path.abspath(
  inspect.getfile(inspect.currentframe())))
  
print(script_directory)
 
 

Output :

Get directory of current Python script

Get directory of current Python script

Get the current working directory using os.getcwd()

In this example, we have used os.getcwd() to get current directory of Python script.

Python3




import os
  
print("File location using os.getcwd():", os.getcwd())
 
 

Output :

File location using os.getcwd(): /home/tuhingfg/Documents/Scripts

Note: Using os.getcwd() doesn’t work as expected when running the Python code from a different directory from the Python script.

Unexpected result when running Python script from a different directory other than script using os.getcwd()

The Python script is placed inside /home/tuhingfg/Documents/Scripts. When we run the script from inside the same folder, it gives the correct script location. But when we change our directory to some other place, it outputs the location of that directory. This is because os.getcwd() considers the directory from where we are executing the script. Based on this, the result of os.getcwd() also varies.

Python3




import os
  
print("File location using os.getcwd():", os.getcwd())
 
 

Output:

Get Script location using os.getcwd()

Get Script location using os.getcwd()

Get the Python Script location using os.path.realpath() Method 

os.path.realpath() can be used to get the path of the current Python script. Actually, os.path.realpath() method in Python is used to get the canonical path of the specified filename by eliminating any symbolic links encountered in the path. A special variable __file__ is passed to the realpath() method to get the path of the Python script.

In this example, the os.getcwd() and __file__ provide two different results. Since we are executing the script from a different folder than the script, os.getcwd() output has changed according to the folder of execution of the script. But __file__ generates the constant result irrespective of the current working directory.

Python3




import os
  
print("File location using os.getcwd():", 
      os.getcwd())
  
print(f"File location using __file__ variable:"+ 
       "{os.path.realpath(os.path.dirname(__file__))}")
 
 

Output:

Get directory Of Python

Get a directory With Python

Note: __file__ is the pathname of the file from which the module was loaded if it was loaded from a file.   



Next Article
Python - List Files in a Directory

N

nikhilaggarwal3
Improve
Article Tags :
  • Python
  • Python file-handling-programs
  • Python os-module-programs
  • python-file-handling
  • python-os-module
Practice Tags :
  • python

Similar Reads

  • Create a directory in Python
    In Python, you can create directories to store and manage your data efficiently. This capability is particularly useful when building applications that require dynamic file handling, such as web scrapers, data processing scripts, or any application that generates output files. Let's discuss differen
    4 min read
  • Get parent of current directory using Python
    In Python, OS module is used to interact with the operating system. It comes under Python's standard utility modules. This module provides a portable way of using operating system dependent functionality. The *os* and *os.path* modules include many functions to interact with the file system. OS modu
    4 min read
  • How to Get directory of Current Script in Python?
    A Parent directory is a directory above another file/directory in a hierarchical file system. Getting the Parent directory is essential in performing certain tasks related to filesystem management. In this article, we will take a look at methods used for obtaining the Parent directory of the current
    4 min read
  • Python - List Files in a Directory
    Sometimes, while working with files in Python, a problem arises with how to get all files in a directory. In this article, we will cover different methods of how to list all file names in a directory in Python. Table of Content What is a Directory in Python?How to List Files in a Directory in Python
    9 min read
  • Python Directory Management
    Python Directory Management refers to handling and interacting with directories (folders) on a filesystem using Python. It includes creating, deleting, navigating and listing directory contents programmatically. Python provides built-in modules like os and os.path and the newer pathlib module, for t
    5 min read
  • Change current working directory with Python
    The OS module in Python is used for interacting with the operating system. This module comes under Python's standard utility module so there is no need to install it externally. All functions in OS module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments t
    2 min read
  • Check if directory contains files using python
    Finding if a directory is empty or not in Python can be achieved using the listdir() method of the os library. OS module in Python provides functions for interacting with the operating system. This module provides a portable way of using operating system dependent functionality. Syntax: os.listdir(
    3 min read
  • Python | os.DirEntry.is_dir() method
    OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.scandir() method of os module yields os.DirEntry objects corresponding to the
    3 min read
  • Python – Import module from different directory
    While working on big projects we may confront a situation where we want to import a module from a different directory. But for some reason, the module may not be imported correctly. Now don’t worry if your module is not imported correctly. In this article, we will discuss ways to import a module fro
    4 min read
  • Python | os.DirEntry.name attribute
    OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.scandir() method of os module yields os.DirEntry objects corresponding to the
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences