python 导入的模块使用了相对路径,导致找不到文件错误

直接上实例:

目录结构:

- 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()
posted @ 2021-03-07 19:24  wztshine  阅读(4722)  评论(0编辑  收藏  举报