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 ?

chenzhongpu
  • 6,193
  • 8
  • 41
  • 79
  • Just use `AFolder/token.json` – cdarke Apr 18 '15 at 06:47
  • 1
    You might be interested in reading about the concept of the ["working directory"](https://en.wikipedia.org/wiki/Working_directory), which you can access via [`os.getcwd()`](https://docs.python.org/2/library/os.html#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. – jedwards Apr 18 '15 at 06:55

1 Answers1

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,485
  • 25
  • 39
abcd
  • 10,215
  • 15
  • 51
  • 85
  • 1
    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. – Dwight Gunning Apr 18 '15 at 06:55