When I get the os.path.dirname()
of a file on Windows, it uses the / character (gets converted to \\ by Windows), but then when I os.path.join()
that path with other things, it uses the \\ character (as expected).
import os
cwd = os.path.dirname(__file__)
print(cwd) # C:/Users/me/Documents/dir1
parent_dir = os.path.join(cwd, '..')
print(parent_dir) # C:/Users/me/Documents/dir1\..
Windows handles this just fine. As per MSDN :
File I/O functions in the Windows API convert "/" to "\\" as part of converting the name to an NT-style name, except when using the "\\\\?\\" prefix as detailed in the following sections.
But why does the use of both slashes occuring in the first place?
EDITS:
I run the command using python myfile.py
from Cygwin shell.
I am using the Anaconda3 distribution, which is installed at C:\\Users\\me\\AppData\\Local\\Continuum\\Anaconda3\\python.exe
.
λ which python
/cygdrive/c/Users/me/AppData/Local/Continuum/Anaconda3/python
Since you're running from cygwin, the paths are not native, but altered for cygwin to be able to work properly (MSYS does the same).
So as a side effect, when python asks for current file, it is returned with slashes.
BUT anaconda is still a native windows distribution, which explains that you get \\
(native os.sep
) when joining strings.
To get __file__
path with native separators ( \\
here), just do:
os.path.normpath(__file__)
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.