直接上實例:
目錄結構:
- a # 文件夾
- a.py
- b.py
- config.txt
在 文件夾 a 下有個 a.py,它使用相對路徑去讀取config.txt的一行數據
def reader():
with open('../config.txt','r') as f:
line = f.readline()
print(line)
if __name__ == '__main__':
reader()
直接運行 a.py , 沒問題:
This is first line: hello world!
請按任意鍵繼續. . .
b.py 和 文件夾a 位於同一層路徑,在 b.py 中導入了 a.py
from a.read import reader
reader()
運行b.py,報錯:提示找不到文件
Traceback (most recent call last):
File "C:\Users\wztshine\Desktop\a\b.py", line 3, in <module>
reader()
File "C:\Users\wztshine\Desktop\a\a\read.py", line 3, in reader
with open('../config.txt','r') as f:
FileNotFoundError: [Errno 2] No such file or directory: '../config.txt'
報錯是因為:運行 b.py 時,此時 python 的路徑是 b.py 所在文件夾的路徑,而不是你以為的 a.py 所在位置的路徑。所以系統會認為你想要在 b.py 的目錄的外層目錄去找 config.txt,肯定找不到,也就報錯了。
解決方法:修改 a.py
import os
path = os.path.dirname(__file__) # 先找到當前文件 a.py 所在的目錄
path = os.path.dirname(path) # 往上倒一層目錄,也就是 config.txt 所在的文件夾
path = os.path.join(path,'config.txt') # 拼接文件的路徑
def reader():
with open(path,'r') as f:
line = f.readline()
print(line)
if __name__ == '__main__':
reader()
