1

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 ?

asked Apr 18, 2015 at 6:39
2
  • Just use AFolder/token.json Commented Apr 18, 2015 at 6:47
  • 1
    You might be interested in reading about the concept of the "working directory", which you can access via os.getcwd(). If you printed os.getcwd() inside check(), you'd see that what it returns differs between when you call it from inside tool.py and inside App.py. If you specify relative paths, it's assumed they're relative from the cwd, and since the cwd changes, the location the tests check also changes. This explains the difference. Commented Apr 18, 2015 at 6:55

1 Answer 1

2

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!

Dwight Gunning
2,53525 silver badges39 bronze badges
answered Apr 18, 2015 at 6:44
Sign up to request clarification or add additional context in comments.

1 Comment

Making the check relative to current path will be more portable. I edited this answer with details. I'll post a separate answer if needed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.