当我在 Windows 上获取文件的 os.path.dirname()
时,它使用/字符(被 Windows 转换为\),但是当我 os. path.join()
该路径与其他东西,它使用\字符(如预期的那样)。
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 处理得很好。根据 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.
但为什么首先使用两个斜杠?
编辑:
我使用 Cygwin shell 中的 python myfile.py
运行命令。
我正在使用 Anaconda3发行版,安装在 C:\Users\me\AppData\Local\Continuum\Anaconda3\python.exe
。
λ which python
/cygdrive/c/Users/me/AppData/Local/Continuum/Anaconda3/python
最佳答案
因为您是从 cygwin 运行的,所以路径不是本地的,而是为了 cygwin 能够正常工作而改变的(MSYS 也是如此)。
因此,作为副作用,当 python 请求当前文件时,返回的是斜杠。
但 anaconda 仍然是原生的 Windows 发行版,这说明在连接字符串时你会得到 \
(原生 os.sep
)。
要获取带有本地分隔符的 __file__
路径(此处为 \
),只需执行以下操作:
os.path.normpath(__file__)
关于python - 为什么 os.path 同时使用 '\' 和 '/' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42401308/