2017-10-13 144 views
0

我有一个python脚本,需要在另一个目录中打开一个文件,这两个目录共享一个共同的父目录,但我不知道父目录可能位于何处,并且需要跨多个操作系统。在相邻目录中打开文件

-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上)。

回答

1

为了运行我们应该使用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 
0

如何os.chdir

os.chdir("../dir2") 
0

OK我发现,在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: 
有效的解决方案