Python3:文件路径问题

时间:2015-04-18 06:39:17

标签: python python-3.x filepath

假设我的Python3项目结构是:

Project
 | App.py
 | AFolder
 |   | tool.py
 |   | token.json

tool.py中,我使用os.path.exists('token.json')来检查Json文件是否退出。正如所料,它返回 true

def check():
   return os.path.exists('token.json')

但是,当我在App.py中调用此内容时,会返回 false

在模块之间调用函数时,文件路径似乎不同。怎么解决?

1 个答案:

答案 0 :(得分:2)

您撰写os.path.exists( . . .的文件所在的位置并不重要。重要的是导入和调用函数时的位置。

因此,在检查文件是否存在时使用完整路径。

def check():
   directory_to_file = '/home/place/where/i/store/files/'
   return os.path.exists(os.path.join(directory_to_file, 'token.json'))
   # Making the check relative to current path will be more portable:
   # return os.path.exists(os.path.join(os.path.dirname(__file__)),'token.json')

这将允许check功能在任何地方工作

相关问题