2

Here is the structure of the folder:

- python
  - python study
    - study.py
    - a.txt

The code in study.py is:

import os

if(os.path.exists("a.txt")):
  print("YES") # my real code is not this
else:
  print("NO")

Usually I open thepython study folder as pycharm project,like this:

s

And the result is YES.

But today I carelessly open the python folder(not python study) as pycharm project and run the code. The result is NO. Finally,I find it refer to the python(project path) instead of the folder of the .py file.What's the purpose of this?

After this, I run this code in cmd,and the result is YES. I think it some time will bring some problems while develop project with other people.(If someone use notepad instead of pycharm to edit code and run code in cmd).

Nikola Lukic
  • 4,001
  • 6
  • 44
  • 75
jizhihaoSAMA
  • 12,336
  • 9
  • 27
  • 49
  • 4
    I dont think this is an issue. You really need to know in which folder you are working in otherwise bigger issues might arrise than the script not running :) – marxmacher Jan 03 '20 at 12:58
  • 1
    os.path.exist("a.txt") will check it this file exist in the current folder where the script is ran out of. – marxmacher Jan 03 '20 at 13:01
  • Possible duplicate of https://stackoverflow.com/questions/786376/how-do-i-run-a-program-with-a-different-working-directory-from-current-from-lin – tripleee Jan 03 '20 at 13:16
  • @marxmacher OK,it's true. – jizhihaoSAMA Jan 03 '20 at 13:17

2 Answers2

3

When you don't specify the absolute path of a file, it is assumed to be in the working directory.

When you open your project from the folder python that is the working directory and os.path.exists('a.txt') is actually looking for the file 'a.txt' in the folder python.

In order to make your script independant of the working directory. You should use relative paths.

You can use __file__ to refer to your script. And you can get the directory of your script using os.path.dirname.

So I think you should modify your code to

import os

fname = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'a.txt')

if(os.path.exists(fname)):
  print("YES")
else:
  print("NO")
abhilb
  • 5,639
  • 2
  • 20
  • 26
  • 1
    actually it's preferred the use `os.path.abspath(__file__)` because `__file__` not always is an absolute path. – marcos Jan 03 '20 at 13:11
  • Using \_\_file\_\_ does not work in [Jupyter notebook as noted here with an alternate solution that's more universal](https://stackoverflow.com/questions/39125532/file-does-not-exisit-in-jupyter-notebook) – DarrylG Jan 03 '20 at 13:34
1

Edit: try this instead of simply calling the path exist, cause it should normalize absolutized version of the pathname path:

os.path.abspath(os.curdir)

By the way, according to this, This function may return False if permission is not granted to execute os.stat() on the requested file, even if the path physically exists. So keep that in mind.

proxyjan
  • 74
  • 4