How to Manage the Current Directory in Python: Get, Change, and List Files

目次

1. Introduction

When programming with Python, the concept of the “current directory (working directory)” is extremely important. The current directory refers to the directory (folder) where the program is being executed and serves as the reference point for file reading and writing in Python. For example, if you specify a relative path such as data/sample.txt inside a Python script, it will search for this file based on the script’s current directory. Therefore, if you do not properly understand the current directory, you may encounter issues such as file not found errors or saving data in unintended folders.

Benefits of Managing the Current Directory in Python

Managing the current directory—retrieving or changing it—has the following benefits in Python:

1. Smooth file reading and writing

Many programs need to read and write data files or configuration files. By properly managing the current directory, the script can obtain and save files in the expected location.

2. Correctly switching between relative and absolute paths

In Python, file paths can be specified using both relative paths (data/sample.txt) and absolute paths (C:/Users/username/project/data/sample.txt or /home/user/project/data/sample.txt). By knowing the current directory, you can more easily determine which method is appropriate.

3. Simplified project management

In large projects, it is common to have multiple folder structures. By changing the current directory when executing a Python script, you can ensure consistent behavior across different environments.

What You Will Learn in This Article

This article provides a detailed explanation of how to get, change, and list the current directory in Python. By learning the following topics step by step, you can improve your directory-handling skills in Python:
  • What is the current directory?
  • How to get the current directory
  • How to change the current directory
  • How to list files in the current directory
  • How to get the directory where the Python script is located
  • Frequently Asked Questions (FAQ) and solutions

Summary

Directory management in Python is essential knowledge for performing file operations. By reading this article, you will deepen your understanding of directory handling in Python and be able to develop programs more smoothly.

2. What is the Current Directory?

When handling files with Python, it is important to properly understand the concept of the current directory (working directory). In this section, we will explain the definition of the current directory and its role.

What is the Current Directory?

The current directory refers to the folder that a Python script is currently using as its reference point. When a Python program runs, file operations with relative paths are performed based on this current directory. For example, consider the following Python script:
file_path = "data/sample.txt"

with open(file_path, "r") as file:
    content = file.read()
This script uses the relative path data/sample.txt. In this case, Python will search for the path “current_directory/data/sample.txt”. In other words, the program’s behavior changes depending on where the current directory is set.

The Role of the Current Directory

Because the current directory affects the Python runtime environment, it plays an important role in the following ways:

1. It serves as the basis for relative paths

When specifying file paths in Python, there are two ways to do so: relative paths and absolute paths.
  • Relative path: Based on the current directory Example: data/sample.txt (accesses sample.txt in the data folder within the current directory)
  • Absolute path: A full path from the root directory Example: C:/Users/username/project/data/sample.txt (Windows) Example: /home/user/project/data/sample.txt (Linux/Mac)
By properly understanding the current directory, you can make effective use of relative paths and improve the portability of your scripts.

2. It allows management of the execution environment

The current directory may vary depending on the environment in which the Python script is run. For example, the current directory can change in the following cases:
Execution methodExample of current directory
Run from the command lineC:/Users/username/project/
Run in VSCode or PyCharmProject root directory
Run in Jupyter NotebookThe directory where the notebook file is located
Changed with os.chdir()os.chdir("/new/path/") can set any directory
By understanding how the current directory works, you can prevent issues such as unintended file loading errors and inconsistent script behavior.

3. Easier project management

Python projects typically have the following folder structure:
/home/user/project/
    ├── main.py  # Main script
    ├── data/
    │   ├── sample.csv
    │   └── config.json
    ├── logs/
    │   ├── app.log
    └── src/
        ├── module1.py
        ├── module2.py
With this kind of project structure, properly setting the current directory makes file reading and writing smoother. In particular, in large-scale projects, it is common to use os.chdir() to unify directories.

How to Check the Current Directory

In Python, you can retrieve the current directory using os.getcwd() or Path.cwd(). ✅ Using the os module
import os

current_directory = os.getcwd()
print("Current directory:", current_directory)
Using the pathlib module (recommended)
from pathlib import Path

current_directory = Path.cwd()
print("Current directory:", current_directory)
The pathlib module, introduced in Python 3.4, provides an object-oriented and easy-to-use approach, so it is recommended for new projects.

Summary

  • The current directory is the folder that a Python script uses as its base.
  • It is important to understand the difference between relative and absolute paths and use them appropriately.
  • The current directory varies depending on the execution environment, so it should be managed consciously.
  • You can check the current directory with os.getcwd() or Path.cwd().

3. How to Get the Current Directory

There are several ways to get the current directory in Python, but the two most common methods use the os module and the pathlib module. In this section, we will explain each method in detail and compare the differences.

What Does Getting the Current Directory Mean?

Getting the current (working) directory allows you to confirm which folder a Python script is using as its base for file operations. This is essential for correctly managing file reading, writing, and the runtime environment. For example, when you run the following Python script, it is important to know which directory is recognized as the current directory:
file_path = "data/sample.txt"

with open(file_path, "r") as file:
    content = file.read()
Depending on where this script is executed, the location of data/sample.txt may change. Therefore, it is critical to clearly identify the current directory.

1. Getting the Current Directory with the os Module

Python’s built-in os module allows you to easily get the current directory.

✅ Using os.getcwd()

import os

current_directory = os.getcwd()
print("Current directory:", current_directory)

✅ Output Example (Windows)

Current directory: C:Usersusernameproject

✅ Output Example (Mac/Linux)

Current directory: /home/user/project
Key Points
  • os.getcwd() returns the absolute (full) path, making it easy to confirm the current directory.
  • Since os is part of Python’s standard library, no additional installation is required.

2. Getting the Current Directory with the pathlib Module

Since Python 3.4, it has been recommended to use the pathlib module to get the current directory. This module provides an object-oriented way of handling file paths.

✅ Using Path.cwd()

from pathlib import Path

current_directory = Path.cwd()
print("Current directory:", current_directory)

✅ Output Example

Current directory: /home/user/project
Key Points
  • Path.cwd() returns the absolute path of the current directory, similar to os.getcwd().
  • Using the Path object makes path operations more intuitive and works well with other file operations in pathlib.
  • Since pathlib was introduced in Python 3.4, it cannot be used in Python 2.

3. Comparison of os.getcwd() vs Path.cwd()

You may wonder which one to use. The features of each are compared below:
Itemos.getcwd()Path.cwd()
Return typeString (str)Path object
SimplicitySimple and easy to useIntuitive object-oriented style
Recommended environmentLegacy code or Python 2New projects with Python 3.4+
Path operationsUses functions like os.path.join()Uses methods of Path objects
ExtensibilityUnifies with traditional methodsIntegrates easily with pathlib features
Conclusion
  • For new projects → Path.cwd() (recommended)
  • For backward compatibility → os.getcwd()

4. Notes When Getting the Current Directory

  1. __file__ cannot be used in Jupyter Notebook
  • os.getcwd() and Path.cwd() work fine, but attempting to use __file__ in Jupyter Notebook will result in an error.
  1. The current directory may differ depending on the command-line environment
  • The current directory can vary depending on where you run the Python script.
  • For example, the current directory in VSCode’s terminal may differ from that in the Windows Command Prompt.
  1. Changing with os.chdir() affects the value of os.getcwd()
  • If you change the current directory, the result of os.getcwd() will change as well. Be careful to avoid unintended behavior.

Summary

  • There are two ways to get the current directory in Python: os.getcwd() and Path.cwd().
  • The traditional os.getcwd() is simple, easy to use, and highly compatible.
  • Path.cwd() is part of the pathlib module and is suitable for object-oriented path operations.
  • Path.cwd() is recommended for new projects.
  • Be aware of differences when working in Jupyter Notebook or different execution environments.

4. How to Change the Current Directory

In Python, it is possible to change the current working directory. This is useful when you want to operate on files in a specific folder or adjust the runtime environment of your script. In this section, we will explain how to change the current directory and the precautions to take.

1. Changing the Current Directory with os.chdir()

To change the current directory, use the os.chdir() function from the os module.

✅ Basic Usage of os.chdir()

import os

# Display the current directory before changing
print("Before change:", os.getcwd())

# Change the current directory
os.chdir("/path/to/new/directory")  # Specify the target directory

# Display the current directory after changing
print("After change:", os.getcwd())

✅ Example Output (before and after)

Before change: /home/user/project
After change: /home/user/project/new_folder
Key Points
  • Using os.chdir("path"), you can change the working directory while the script is running.
  • After changing, all relative paths will be processed based on the new current directory.

2. Using Absolute vs. Relative Paths with os.chdir()

When changing directories with os.chdir(), you can specify either an absolute path or a relative path.

✅ Using an Absolute Path

os.chdir("/home/user/project/new_folder")  # Linux / Mac
os.chdir("C:Usersusernameprojectnew_folder")  # Windows
  • Absolute paths work reliably in any environment.
  • This is the recommended method.

✅ Using a Relative Path

os.chdir("new_folder")   # Move into "new_folder" inside the current directory
os.chdir("../")          # Move up one directory
os.chdir("../../")       # Move up two directories
  • Relative paths change directories based on the current directory, making them more portable across environments.
  • However, if the current directory is unclear, it may cause unexpected behavior.

3. Error Handling with os.chdir()

If the specified directory does not exist, Python will raise a FileNotFoundError. To avoid this, it is good practice to check whether the directory exists before changing.

✅ Example of Error Handling

import os

new_directory = "/path/to/nonexistent/directory"

# Check if the directory exists before changing
if os.path.exists(new_directory):
    os.chdir(new_directory)
    print("Directory changed:", os.getcwd())
else:
    print("Error: Specified directory does not exist.")

✅ Example Output (if the directory does not exist)

Error: Specified directory does not exist.
Key Points
  • Use os.path.exists(path) to check if a directory exists before changing.
  • If the directory does not exist, FileNotFoundError will be raised, so adding exception handling prevents errors.

4. Restoring the Original Directory

After changing the current directory, you may want to return to the original one. You can save the original directory beforehand and restore it afterward.

✅ Save the Original Directory

import os

# Save the current directory
original_directory = os.getcwd()

# Change to another directory
os.chdir("/path/to/new/directory")
print("After change:", os.getcwd())

# Return to the original directory
os.chdir(original_directory)
print("Restored to original:", os.getcwd())

✅ Example Output

After change: /home/user/new_folder
Restored to original: /home/user/project
Key Points
  • By saving the original directory with original_directory = os.getcwd(), you can easily restore it using os.chdir(original_directory).
  • When running multiple scripts together, forgetting to restore may cause unintended file operations.

5. Scope of os.chdir() Effects

When you change the current directory with os.chdir(), the current directory of the entire Python script is affected, which may cause unintended consequences.

✅ Example: Issues After Changing the Current Directory

import os

# Change to another directory
os.chdir("/path/to/new/directory")

# If other scripts rely on the previous directory
with open("config.json", "r") as file:
    config = file.read()  # May raise an unexpected error
This code may fail because config.json was expected in the original folder but is now searched in the new directory. Therefore, be cautious of script behavior after changing the current directory.

Summary

  • You can change the current directory with os.chdir().
  • Absolute paths are safer, but relative paths can also be useful.
  • Check for errors to avoid changing to non-existent directories.
  • Save the original directory to restore it later if needed.
  • Remember that changing the current directory affects the entire script and may cause unintended errors.
侍エンジニア塾

5. How to List Files in the Current Directory

In Python, you can retrieve a list of files and folders within the current directory. This is useful for listing files of a specific type or processing multiple files at once. In this section, we will explain in detail how to list files using the os module and the pathlib module.

1. Listing Files with os.listdir()

The os module in Python provides the os.listdir() function to get a list of files and folders in a directory.

✅ Basic Usage of os.listdir()

import os

# Get files and folders in the current directory
files_and_folders = os.listdir()

print("Contents of current directory:", files_and_folders)

✅ Example Output

Contents of current directory: ['file1.txt', 'file2.csv', 'images', 'script.py']
Key Points
  • os.listdir() retrieves both files and folders.
  • The returned list contains filenames with extensions, so you may need to filter files by type.

2. Getting Only Files with os.listdir()

Since os.listdir() retrieves all items (both files and folders), you can combine it with os.path.isfile() to extract only files.

✅ Example: Get Only Files

import os

# Get only files in the current directory
files = [f for f in os.listdir() if os.path.isfile(f)]

print("Files in current directory:", files)

✅ Example Output

Files in current directory: ['file1.txt', 'file2.csv', 'script.py']
Key Points
  • os.path.isfile(f) filters out folders and extracts only files.
  • List comprehensions allow concise and clean code.

3. Getting Files with a Specific Extension Using os.listdir()

Sometimes, you may want to list only files with a specific extension (e.g., .txt or .csv). You can use list comprehensions with string filtering.

✅ Example: Get Only .txt Files

import os

# Get only .txt files in the current directory
txt_files = [f for f in os.listdir() if f.endswith('.txt')]

print(".txt files:", txt_files)

✅ Example Output

.txt files: ['file1.txt', 'notes.txt']
Key Points
  • By using f.endswith('.txt'), you can filter only files ending with .txt.
  • This can be adapted for other extensions such as .csv or .log.

4. Listing Files with pathlib

Since Python 3.4, you can use the pathlib module to list files. With its object-oriented style, pathlib allows more intuitive file handling.

✅ Using Path.iterdir() to List Files

from pathlib import Path

# Get files and folders in the current directory
files_and_folders = list(Path.cwd().iterdir())

print("Contents of current directory:", files_and_folders)

✅ Example Output

Contents of current directory: [PosixPath('file1.txt'), PosixPath('file2.csv'), PosixPath('images'), PosixPath('script.py')]
Key Points
  • Path.cwd().iterdir() retrieves items in the current directory as Path objects.
  • Converting them to a list makes them easier to handle.

5. Getting Only Files with pathlib

With Path.iterdir(), it is also easy to get only files.

✅ Example: Get Only Files

from pathlib import Path

# Get only files in the current directory
files = [f for f in Path.cwd().iterdir() if f.is_file()]

print("Files in current directory:", files)

✅ Example Output

Files in current directory: [PosixPath('file1.txt'), PosixPath('file2.csv'), PosixPath('script.py')]
Key Points
  • f.is_file() excludes folders and returns only files.
  • Using Path objects makes it easy to manipulate file paths.

6. Comparison: os.listdir() vs pathlib

MethodFeaturesRecommended Use
os.listdir()Simple and fastWhen prioritizing compatibility
os.path.isfile()Retrieve only filesUse together with os.listdir()
Path.iterdir()Object-oriented and intuitiveWhen utilizing pathlib
Conclusion
  • Legacy code → os.listdir() (simple and fast)
  • New projects → pathlib.Path().iterdir() (object-oriented and easier to use)

Summary

  • os.listdir() makes it easy to get files and folders in the current directory.
  • With os.path.isfile(), you can exclude folders and get only files.
  • pathlib.Path().iterdir() enables object-oriented path handling for more intuitive file operations.
The next section explains in detail how to get the directory where the script is located.

6. How to Get the Directory of the Running Script

Knowing the directory where a Python script is located is important when loading external files or performing tasks that depend on the script’s location. In this section, we explain how to get the script’s directory and how to use it effectively.

1. Using the __file__ Variable

In Python, the __file__ variable stores the file path of the script currently being executed. By combining it with os.path.dirname(), you can obtain the directory where the script is located.

✅ Basic Example Using __file__

import os

# Get the absolute path of the script
script_path = os.path.abspath(__file__)

# Get the directory containing the script
script_directory = os.path.dirname(script_path)

print("Script absolute path:", script_path)
print("Script directory:", script_directory)

✅ Example Output

Script absolute path: /home/user/project/script.py
Script directory: /home/user/project
Key Points
  • The __file__ variable is a special variable that stores the file path of the script.
  • os.path.abspath(__file__) returns the absolute path of the script.
  • os.path.dirname(path) retrieves the directory where the script is located.
Note on Execution Environments
  • __file__ cannot be used in Jupyter Notebook.
  • It is only available when a script file exists, so in Jupyter Notebook, it raises an error.
  • In Notebook environments, use os.getcwd() instead.

2. Using pathlib to Get the Script’s Directory

Since Python 3.4, you can also use pathlib to get the script directory in a more intuitive way.

✅ Example Using pathlib

from pathlib import Path

# Get the script’s directory
script_directory = Path(__file__).resolve().parent

print("Script directory:", script_directory)

✅ Example Output

Script directory: /home/user/project
Key Points
  • Path(__file__).resolve() returns the absolute path of the script.
  • Using .parent retrieves the parent directory where the script is located.
  • Because it is object-oriented, pathlib is recommended for new projects.
Comparison: os vs. pathlib
MethodFeaturesRecommended Use
os.path.dirname(os.path.abspath(__file__))Traditional methodWhen prioritizing compatibility
Path(__file__).resolve().parentObject-oriented and intuitiveFor Python 3.4+ new projects

3. Setting the Script’s Directory as the Current Directory

By setting the script’s directory as the current directory, you can ensure consistent behavior across environments.

✅ Example: Using os.chdir() to Change

import os

# Get the script’s directory
script_directory = os.path.dirname(os.path.abspath(__file__))

# Set the current directory to the script’s location
os.chdir(script_directory)

print("Current directory set to script’s location:", os.getcwd())

✅ Example Output

Current directory set to script’s location: /home/user/project
Key Points
  • Using os.chdir(script_directory) sets the current directory to the script’s folder.
  • This ensures programs using relative paths work correctly regardless of where they are run.
For Jupyter Notebook, since __file__ cannot be used, use os.getcwd() instead.
import os

# In Jupyter Notebook, get the current directory directly
script_directory = os.getcwd()
print("Current directory in Jupyter Notebook:", script_directory)

4. Practical Example of Using the Script Directory

By retrieving the script’s directory, you can load configuration files or data files relative to the script’s location.

✅ Example: Open a File Based on the Script’s Directory

import os

# Get the script’s directory
script_directory = os.path.dirname(os.path.abspath(__file__))

# Build the path for a file located in the same folder as the script
file_path = os.path.join(script_directory, "data.txt")

# Open the file
with open(file_path, "r") as file:
    content = file.read()

print("File content:", content)

✅ Example Output

File content: This is the content of a file in the script’s directory.
Key Points
  • Using os.path.join(script_directory, "filename") allows you to open files relative to the script’s location.
  • This improves portability since the script always refers to files in the same directory regardless of execution environment.

Summary

  • To get the script’s directory, use __file__.
  • Since Python 3.4, pathlib.Path(__file__).resolve().parent provides a more intuitive option.
  • You can set the script’s directory as the current directory using os.chdir().
  • In Jupyter Notebook, since __file__ is unavailable, use os.getcwd() instead.
  • Using the script’s directory as a reference makes your code more portable.

7. FAQ: Frequently Asked Questions

Here are answers to common questions about handling the current directory in Python.

Q1. What is the difference between os.getcwd() and __file__?

  • os.getcwd(): Returns the current working directory (the directory where the script is executed).
  • __file__: Stores the absolute path of the script file itself.
Usage Guide
  • If you want to know the environment where the script is running → Use os.getcwd().
  • If you want to know the script’s location → Use __file__.

Q2. Why does the current directory differ when running from VSCode or Jupyter Notebook?

The current directory depends on the execution environment:
  • Command line: The directory where the script is run.
  • VSCode / PyCharm: Often the project root directory.
  • Jupyter Notebook: The directory where the notebook file is located.
➡️ Since behavior varies by environment, it is recommended to explicitly set the current directory within the script.

Q3. Can I use relative paths without worrying about the current directory?

Relative paths work as long as the current directory is as expected. However, if the current directory differs from what you assumed:
  • Files may not be found.
  • Data may be saved to the wrong location.
✅ Solution:
  • Set the current directory to the script’s location using os.chdir().
  • Or, always build file paths relative to __file__ (recommended).

Q4. What happens if I use os.chdir() in the middle of a script?

  • After calling os.chdir(), the current directory changes globally.
  • All subsequent relative paths will be resolved based on the new directory.
  • If other code expects the old directory, errors may occur.
Best Practice: Save the original directory with os.getcwd() and restore it when necessary.

Q5. Why does __file__ not work in Jupyter Notebook?

  • Jupyter Notebook does not save the executed code as a file, so __file__ is undefined.
  • Instead, use os.getcwd() to get the working directory.

Q6. How can I list files in subfolders as well?

  • Use os.walk() or Path.rglob() to traverse directories recursively.

✅ Example with os.walk()

import os

for root, dirs, files in os.walk("."):
    print("Current folder:", root)
    print("Files:", files)

✅ Example with pathlib.Path.rglob()

from pathlib import Path

# Get all .txt files in subfolders
txt_files = list(Path.cwd().rglob("*.txt"))
print(txt_files)

Q7. Which is recommended: os or pathlib?

  • os module: Traditional, widely supported, compatible with legacy code.
  • pathlib module: Object-oriented, easier to read, recommended for Python 3.4+.
➡️ Conclusion: For new projects, pathlib is recommended, but for legacy projects, os is still effective.

Summary

  • The difference between os.getcwd() and __file__ is important to understand.
  • The current directory differs depending on the execution environment (CLI, IDE, Jupyter).
  • Relative paths are convenient but risky if the current directory is unclear.
  • When changing directories with os.chdir(), remember to restore the original if needed.
  • In Jupyter Notebook, __file__ cannot be used.
  • Use os.walk() or Path.rglob() for recursive file listing.

8. Summary

In this article, we explained how to handle the current directory in Python, from basic concepts to practical usage.

Key Points Recap

  • The current directory (working directory) is the base folder used when executing a Python program.
  • You can get the current directory using os.getcwd() or Path.cwd().
  • You can change the current directory with os.chdir().
  • You can list files in the current directory using os.listdir() or Path.iterdir().
  • You can get the script’s directory using __file__ or pathlib.
  • The current directory differs depending on the environment (command line, IDE, Jupyter Notebook).
  • Be careful when using relative paths, and consider always referencing the script’s directory for stable operation.

Best Practices for Directory Handling

  • For new projects → Use pathlib (object-oriented and intuitive)
  • For legacy projects → os module is still useful
  • In Jupyter Notebook, use os.getcwd() since __file__ is unavailable
  • When using relative paths, explicitly set the current directory to avoid unexpected errors

Final Thoughts

Proper management of the current directory is an essential skill for Python developers. By mastering how to get, change, and use directories, you can:
  • Avoid file not found errors
  • Make your programs more portable
  • Ensure consistent behavior across environments
If you practice the techniques introduced in this article, your Python file operations will become more robust and easier to maintain.
RUNTEQ(ランテック)|超実戦型エンジニア育成スクール