Opening Files in the Same Directory
In Python, you can read or write files using the built‑in open() function. When the target file resides in the same folder as your script, a relative path makes the code portable and easy to maintain.
The following example loads a configuration file named settings.cfg located in the same directory:
config_path = "./settings.cfg"
with open(config_path, 'r') as handler:
data = handler.read()
print(data)
Here "./settings.cfg" is the relative path. The leading ./ explicitly refers to the current working directory. The with statement ensures the file is properly closed after reading.
Sequence Diagram
The following diagram shows the interaction between the Python script and the file:
sequenceDiagram
participant Python
participant File
Python->>File: open file with relative path
File-->>Python: return file contents
Python sends an open request using the filename, and the file system returns the content.
Journey Diagram
A high‑level view of the same process can be illustrated with a journey:
journey
title Opening a File in the Same Directory
section Discover File
Python: - Notices a file is needed
- Opens file using relative path
- Reads all content
section Return Contents
File: - Sends content back to Python
The journey highlights the two‑phase flow: the script decides to open a local file and then receives the file’s data.