前言
先讓我們來看看一個(gè)用到相對(duì)文件路徑的函數(shù)調(diào)用的問題。假設(shè)現(xiàn)在有兩個(gè)腳本文件main.py和func.py,他們的路徑關(guān)系是:
.
|--dir1
|--main.py
|--dir2
|--func.py
|--test.txt
func.py的作用是提供load_txt()函數(shù),讀取同級(jí)目錄下test.txt文件中的內(nèi)容并返回。
# func.py
def load_txt()
filename = './test.txt'
return open(filenamem, 'r').read()
假設(shè)現(xiàn)在在main.py中調(diào)用load_txt()函數(shù):
# main.py
from dir2 import func
if __name__ == '__main__':
print func.load_txt()
這個(gè)時(shí)候會(huì)報(bào)類似找不到文件test.txt的錯(cuò)誤。
為什么會(huì)這樣呢?這是因?yàn)樵诤瘮?shù)調(diào)用的過程中,當(dāng)前路徑.代表的是被執(zhí)行的腳本文件的所在路徑。在這個(gè)情況中,.表示的就是main.py的所在路徑,所以load_txt()函數(shù)會(huì)在dir1文件夾中尋找test.txt文件。
那么怎么樣才能在函數(shù)調(diào)用的過程中保持相對(duì)路徑的不變呢?
方法
在網(wǎng)上有相當(dāng)多的教程都有提到這個(gè)Python中相對(duì)文件路徑的問題,但是大部分都沒有提及到在這種情況下的解決辦法。
在以下的三個(gè)函數(shù)中,第一個(gè)和第二個(gè)是大部分教程中的解決辦法,但是這樣是錯(cuò)誤的,因?yàn)榈谝粋€(gè)和第二個(gè)函數(shù)所獲取的"當(dāng)前文件路徑"都是被執(zhí)行的腳本文件的所在路徑,只有第三個(gè)函數(shù)返回的當(dāng)前文件路徑才是真正的、該函數(shù)所在的腳本文件的所在路徑
def get_cur_path1():
import os
return os.path.abspath(os.curdir)
def get_cur_path2():
import sys
return sys.argv[0]
def get_cur_path3():
import os
return os.path.dirname(__file__)
因此,解決辦法如下。修改func.py中的讀取函數(shù)如下即可:
# func.py
import os
def load_txt()
module_path = os.path.dirname(__file__)
filename = modelu_path + '/test.txt'
return open(filenamem, 'r').read()