Reputation:
I'm a beginner. My system is win10 Pro,and I use python3.X.
I use this code to test function "os.path.join()" and "os.path.dirname()".
import os
print(os.path.join(os.path.dirname(__file__), "dateConfig.ini"))
The output is:
E:/test_opencv\dateConfig.ini
I found os.path.join() use "/",but os.path.dirname() use "\",why?
If I want to use the same separator,all is '/' or '\',what should I do?
Upvotes: 2
Views: 975
Reputation: 140148
that's because __file__
contains the script name as passed in argument.
If you run
python E:/test_opencv/myscript.py
then __file__
contains exactly the argument passed to python
. (Windows has os.altsep
as /
, because it can use this alternate separator)
A good way of fixing that is to use os.path.normpath
to replace the alternate separator by the official separator, remove double separators, ...
print(os.path.join(os.path.normpath(os.path.dirname(__file__)),"dateConfig.ini"))
Normalizing the path can be useful when running legacy Windows commands that don't support slashes/consider them as option switches. If you just use the path to pass to open
, you don't need that.
Upvotes: 1