Python – Read file from sibling directory
Last Updated :
06 Jun, 2021
In this article, we will discuss the method to read files from the sibling directory in Python. First, create two folders in a root folder, and one folder will contain the python file and the other will contain the file which is to be read. Below is the dictionary tree:
Directory Tree:
root :
|
|__Sibling_1:
| \__demo.py
|
|__Sibling_2:
| \__file.txt
Here Sibling_1 and Sibling_2 are siblings. We are going to discuss the method to read data from file.text in demo.py which exists in the sibling folder. We will be using the os module to change the current working directory to a directory having file.txt.
file.txt:
This is the data that need to be read!!
The steps will be as follows:
1. Importing os module and storing the path of demo.py in a variable called path. The os.path.realpath(__file__) method will give the path where the file demo.py exists which will be ‘D:\root\Sibling_1\demo.py’.
Python
import os
path = os.path.realpath(__file__)
print (path)
|
Output:
'D:\root\Sibling_1\demo.py'
2. Getting the directory using os.path.dirname() where demo.py exists and storing it in variable dir.
Python
import os
path = os.path.realpath(__file__)
dir = os.path.dirname(path)
print ( dir )
|
Output:
'D:\root\Sibling_1'
3. Replacing the folder name in dir string from Sibling_1 to Sibling_2, so that now dir has directory ‘D:\root\Sibling_2’ where file.txt exist. Now we will use the method os.chdir() to change the working directory from the current directory to the directory stored in dir.
Python
import os
path = os.path.realpath(__file__)
dir = os.path.dirname(path)
dir = dir .replace( 'Sibling_1' , 'Sibling_2' )
os.chdir( dir )
print ( dir )
|
Output:
'D:\root\Sibling_2'
4. Now as the directory is changed to a sibling folder we can use the open() method to directly open and read any file in the folder.
Python
import os
path = os.path.realpath(__file__)
dir = os.path.dirname(path)
dir = dir .replace( 'Sibling_1' , 'Sibling_2' )
os.chdir( dir )
f = open ( 'file.txt' )
data = f.read()
print (data)
|
Output:
This is the data that need to be read!!
Share your thoughts in the comments
Please Login to comment...