Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to open a file in the same directory as a Python script?
In Python, it is a common scenario that the files we want to work with should be placed in the same folder as the script itself. Simply referencing a filename like "data.txt" may not always work as expected, especially when the script is executed from a different working directory.
The best way is to locate the scripts in the actual location using the __file__ variable along with the os or pathlib modules. In this article, we are going to see the different approaches to open a file in the same directory as a Python script.
Using the os Module
The os module offers different tools for interacting with the filesystem in a platform-independent way. We have the methods os.path.dirname() and os.path.join() which we can use to get the absolute path to the directory and make the script work from the same directory.
Syntax
import os # Get script directory base_dir = os.path.dirname(os.path.abspath(__file__)) # Join with filename file_path = os.path.join(base_dir, 'filename.txt')
Example
In this example, we are going to learn how to open a file in the same directory as a Python script using the os module ?
import os
# Create a sample file for demonstration
sample_content = """Hello, welcome to Tutorialspoint.
Have a happy learning."""
with open('file1.txt', 'w') as f:
f.write(sample_content)
# Locate the folder where the script is stored
base_dir = os.path.dirname(os.path.abspath(__file__))
# Combine folder path with the target file name
file_path = os.path.join(base_dir, 'file1.txt')
# Read the file content
with open(file_path, 'r') as f:
data = f.read()
print(data)
Following is the output of the above program ?
Hello, welcome to Tutorialspoint. Have a happy learning.
Using pathlib Module
The pathlib module was introduced in Python 3.4, which offers an object-oriented approach for handling file system paths. In this module, we have the __file__ attribute to work with files in the same directory.
Syntax
from pathlib import Path # Get script directory base_dir = Path(__file__).parent # Join with filename using / operator file_path = base_dir / 'filename.txt'
Example
Here in this example, we are going to show how to open a file in the same directory as a Python script using the pathlib module ?
from pathlib import Path
# Create a sample file for demonstration
sample_content = """Hello, welcome to Tutorialspoint.
Have a happy learning."""
with open('file1.txt', 'w') as f:
f.write(sample_content)
# Get the current script's folder
base_dir = Path(__file__).parent
# Form the complete file path
file_path = base_dir / 'file1.txt'
# Open and display the file contents
with file_path.open('r') as f:
data = f.read()
print(data)
Here is the output of the above program ?
Hello, welcome to Tutorialspoint. Have a happy learning.
Using os.getcwd() as Fallback
Note: When we use environments such as Jupyter Notebooks or interactive shells, then the __file__ variable isn't available. In such cases, we can use the current working directory using os.getcwd() method.
Following is the example, which shows how to use the method os.getcwd() ?
import os
# Create a sample file for demonstration
sample_content = """Hello, welcome to Tutorialspoint.
Have a happy learning."""
with open('file1.txt', 'w') as f:
f.write(sample_content)
# Use the current directory as fallback
base_dir = os.getcwd()
file_path = os.path.join(base_dir, 'file1.txt')
# Open and read the file
with open(file_path, 'r') as f:
print(f.read())
Below is the output of the above program ?
Hello, welcome to Tutorialspoint. Have a happy learning.
Comparison
| Method | Python Version | Best For | Limitations |
|---|---|---|---|
os.path |
All versions | Legacy code compatibility | String-based paths |
pathlib |
3.4+ | Modern object-oriented approach | Requires Python 3.4+ |
os.getcwd() |
All versions | Interactive environments | Uses current working directory |
Conclusion
Use pathlib for modern Python applications as it provides cleaner syntax. Use os.path for compatibility with older Python versions. Use os.getcwd() when __file__ is not available in interactive environments.
