Reputation: 6871
Suppose my Python3
project structure is :
Project
| App.py
| AFolder
| | tool.py
| | token.json
In tool.py
, I use os.path.exists('token.json')
to check whether the Json file exits. As expected, it returns true.
def check():
return os.path.exists('token.json')
However, when I call this in App.py
, it returns false.
It seems file path is different when calling functions between modules. How to solve it ?
Upvotes: 1
Views: 825
Reputation: 10791
It doesn't matter where the file in which you've written os.path.exists( . . .
is. What matters is where you are when you import and call the function.
So, use the full path when you check whether the file 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')
This will allow the check
function to work anywhere!
Upvotes: 2