2014-02-27 42 views
1

我有一個小文本(XML)文件,我想要加載一個Python函數。文本文件的位置始終與Python函數代碼的固定相對位置。Python:檢查數據文件是否存在相對於源代碼文件

例如,我的本地計算機上,文件text.xml和mycode.py可以駐留在:

/a/b/text.xml 
/a/c/mycode.py 

後來在運行時,這些文件可以駐留在:

/mnt/x/b/text.xml 
/mnt/x/c/mycode.py 

我如何確保我可以加載文件?我需要絕對路徑嗎?我看到我可以使用os.path.isfile,但假設我有一個路徑。

回答

1

你可以做一個電話如下:

import os 
BASE_DIR = os.path.dirname(os.path.realpath(__file__)) 

這將讓你的你正在調用的python文件的目錄mycode.py

然後訪問xml文件就像這樣簡單:

xml_file = "{}/../text.xml".format(BASE_DIR) 
fin = open(xml_file, 'r+') 
1

如果這兩個目錄的父目錄總是相同的這應該工作:

import os 
path_to_script = os.path.realpath(__file__) 
parent_directory = os.path.dirname(path_to_script) 

for root, dirs, files in os.walk(parent_directory): 
    for file in files: 
     if file == 'text.xml': 
      path_to_xml = os.path.join(root, file) 
1

可以使用特殊變量__file__它給你當前的文件名(見http://docs.python.org/2/reference/datamodel.html)。

所以在你的第一個例子,你可以text.xml這種方式mycode.py參考:

xml_path = os.path.join(__file__, '..', '..', 'text.xml')