打开相邻目录中的文件
Open file in adjacent directory
我有一个 python 脚本需要打开另一个目录中的文件,这两个目录共享一个共同的父目录,但我不知道父目录可能位于何处并且它需要跨多个 OS.
-Parent
-dir1
-file.txt
-dir2
-script.py
我尝试了另一个答案,但它不起作用:
import os.path
current_path = os.path.dirname(__file__)
file_path = os.path.relpath('..\Parent\dir1\file.txt', current_path)
with open(file_path, 'rb') as afile:
但我只知道路径未被识别(在本例中为 Linux)。
怎么样os.chdir
:
os.chdir("../dir2")
为了 运行 多个 os 我们应该使用 os.path。
下面的代码可以 运行 来自任何目录的脚本。
import os
script_path = os.path.realpath(__file__)
parent_path = os.path.dirname(script_path)
file_path = os.path.join(os.path.sep,parent_path,"dir1","file1.txt")
print file_path
好的,我找到了适用于 Linux 和 Windows
的解决方案
import os.path
current_path = os.path.dirname(__file__)
file_path = os.path.abspath(os.path.join(current_path, "..", "dir1", "file.txt"))
with open(file_path, 'rb') as afile:
我有一个 python 脚本需要打开另一个目录中的文件,这两个目录共享一个共同的父目录,但我不知道父目录可能位于何处并且它需要跨多个 OS.
-Parent
-dir1
-file.txt
-dir2
-script.py
我尝试了另一个答案,但它不起作用:
import os.path
current_path = os.path.dirname(__file__)
file_path = os.path.relpath('..\Parent\dir1\file.txt', current_path)
with open(file_path, 'rb') as afile:
但我只知道路径未被识别(在本例中为 Linux)。
怎么样os.chdir
:
os.chdir("../dir2")
为了 运行 多个 os 我们应该使用 os.path。 下面的代码可以 运行 来自任何目录的脚本。
import os
script_path = os.path.realpath(__file__)
parent_path = os.path.dirname(script_path)
file_path = os.path.join(os.path.sep,parent_path,"dir1","file1.txt")
print file_path
好的,我找到了适用于 Linux 和 Windows
的解决方案import os.path
current_path = os.path.dirname(__file__)
file_path = os.path.abspath(os.path.join(current_path, "..", "dir1", "file.txt"))
with open(file_path, 'rb') as afile: