Python - 从兄弟目录读取文件
在本文中,我们将讨论在Python从兄弟目录中读取文件的方法。首先,在根文件夹中创建两个文件夹,一个文件夹包含Python文件,另一个文件夹包含要读取的文件。下面是字典树:
目录树:
root :
|
|__Sibling_1:
| \__demo.py
|
|__Sibling_2:
| \__file.txt
这里 Sibling_1 和 Sibling_2 是兄弟姐妹。我们将讨论从存在于同级文件夹中的 demo.py 中的 file.text 中读取数据的方法。我们将使用 os 模块将当前工作目录更改为包含 file.txt 的目录。
文件.txt:
This is the data that need to be read!!
步骤如下:
1. 导入os模块,将demo.py的路径存放在一个名为path的变量中。 os.path.realpath(__file__) 方法将给出文件 demo.py 所在的路径,即“D:\root\Sibling_1\demo.py”。
Python
# importing os module
import os
# gives the path of demo.py
path = os.path.realpath(__file__)
print(path)
Python
import os
# gives the path of demo.py
path = os.path.realpath(__file__)
# gives the directory where demo.py
# exists
dir = os.path.dirname(path)
print(dir)
Python
import os
path = os.path.realpath(__file__)
dir = os.path.dirname(path)
# replaces folder name of Sibling_1 to
# Sibling_2 in directory
dir = dir.replace('Sibling_1', 'Sibling_2')
# changes the current directory to Sibling_2
# folder
os.chdir(dir)
print(dir)
Python
# importing os module
import os
# gives the path of demo.py
path = os.path.realpath(__file__)
# gives the directory where demo.py
# exists
dir = os.path.dirname(path)
# replaces folder name of Sibling_1 to
# Sibling_2 in directory
dir = dir.replace('Sibling_1', 'Sibling_2')
# changes the current directory to
# Sibling_2 folder
os.chdir(dir)
# opening file.txt which is to read
f = open('file.txt')
# reading data from file.txt and storing
# it in data
data = f.read()
# printing data
print(data)
输出:
'D:\root\Sibling_1\demo.py'
2. 使用 os.path.dirname() 获取 demo.py 所在的目录并将其存储在变量 dir 中。
Python
import os
# gives the path of demo.py
path = os.path.realpath(__file__)
# gives the directory where demo.py
# exists
dir = os.path.dirname(path)
print(dir)
输出:
'D:\root\Sibling_1'
3. 将 dir字符串的文件夹名称从 Sibling_1 替换为 Sibling_2,以便现在 dir 具有目录 'D:\root\Sibling_2',其中 file.txt 存在。现在我们将使用方法 os.chdir() 将工作目录从当前目录更改为存储在 dir 中的目录。
Python
import os
path = os.path.realpath(__file__)
dir = os.path.dirname(path)
# replaces folder name of Sibling_1 to
# Sibling_2 in directory
dir = dir.replace('Sibling_1', 'Sibling_2')
# changes the current directory to Sibling_2
# folder
os.chdir(dir)
print(dir)
输出:
'D:\root\Sibling_2'
4. 现在,当目录更改为兄弟文件夹时,我们可以使用 open() 方法直接打开和读取文件夹中的任何文件。
Python
# importing os module
import os
# gives the path of demo.py
path = os.path.realpath(__file__)
# gives the directory where demo.py
# exists
dir = os.path.dirname(path)
# replaces folder name of Sibling_1 to
# Sibling_2 in directory
dir = dir.replace('Sibling_1', 'Sibling_2')
# changes the current directory to
# Sibling_2 folder
os.chdir(dir)
# opening file.txt which is to read
f = open('file.txt')
# reading data from file.txt and storing
# it in data
data = f.read()
# printing data
print(data)
输出:
This is the data that need to be read!!