简体   繁体   中英

Why does os.path refer to the project path instead of file path?

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 the python study folder as pycharm project,like this:

秒

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).

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")

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM