假设我的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。
在模块间调用函数时,文件路径似乎是不同的。如何解决这个问题?
发布于 2015-04-18 06:44:06
编写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函数在任何地方工作!
https://stackoverflow.com/questions/29713866
复制相似问题