我正在尝试学习python并正在制作一个将输出脚本的程序.我想使用os.path.join,但我很困惑.根据文件,如果我说:
os.path.join('c:', 'sourcedir')
Run Code Online (Sandbox Code Playgroud)
我得到"C:sourcedir".根据文档,这是正常的,对吧?
但是当我使用copytree命令时,Python会以所需的方式输出它,例如:
import shutil
src = os.path.join('c:', 'src')
dst = os.path.join('c:', 'dst')
shutil.copytree(src, dst)
Run Code Online (Sandbox Code Playgroud)
这是我得到的错误代码:
WindowsError: [Error 3] The system cannot find the path specified: 'C:src/*.*'
如果我换行os.path.join与os.path.normpath我得到同样的错误.
如果os.path.join不能以这种方式使用,那么我对其目的感到困惑.
根据Stack Overflow建议的页面,不应该在连接中使用斜杠 - 这是正确的,我假设?
就在我以为我已经看到了Windows路径问题时,我现在遇到的情况只有在使用'/'(正斜杠)作为路径分隔符时才会失败:
C:\temp\tcbugs>mkdir "dir1 with spaces"
C:\temp\tcbugs>echo hi > "dir1 with spaces"\foo.txt
C:\temp\tcbugs>type "dir1 with spaces\foo.txt"
hi
C:\temp\tcbugs>type "dir1 with spaces/foo.txt"
The system cannot find the file specified.
Run Code Online (Sandbox Code Playgroud)
特别有趣的是它似乎是特定于cmd.exe shell而不是在PowerShell中出现(也不是在win32 API中):
PS C:\temp\tcbugs> type 'dir1 with spaces/foo.txt'
hi
Run Code Online (Sandbox Code Playgroud)
另一个兴趣点是使用'cd'更改目录并使用'/'作为cmd.exe的路径分隔符确实有效:
C:\temp\tcbugs>mkdir dir2_no_spaces
C:\temp\tcbugs>cd ./dir2_no_spaces
C:\temp\tcbugs\dir2_no_spaces>cd ..
Run Code Online (Sandbox Code Playgroud)
然而,我无法在网上或MSDN的常用文档中找到任何对此特定问题的引用:
这引出了我的问题:为什么会发生这种情况,是否有一个明确的来源记录了这个怪癖?
更新:
dbenham指出,无论空格是否在目录名称中,问题都存在,因此在标题和问题正文中删除了对它的引用.还添加了一个有效的"cd ./"示例,而其他命令则没有.