Windows 上的 Python os.path.join [英] Python os.path.join on Windows
问题描述
我正在尝试学习 python 并且正在制作一个可以输出脚本的程序.我想使用 os.path.join,但我很困惑.根据 docs 如果我说:
os.path.join('c:', 'sourcedir')
我得到 "C:sourcedir"
.根据文档,这是正常的,对吗?
但是当我使用 copytree 命令时,Python 会以想要的方式输出它,例如:
导入shutilsrc = os.path.join('c:', 'src')dst = os.path.join('c:', 'dst')关闭.copytree(src, dst)
这是我得到的错误代码:
<前>WindowsError: [Error 3] 系统找不到指定的路径:'C:src/*.*'如果我用 os.path.normpath
包裹 os.path.join
,我会得到同样的错误.
如果这个 os.path.join
不能这样使用,那么我对它的用途感到困惑.
根据 Stack Overflow 建议的页面,在 join 中不应该使用斜杠——我认为是正确的吗?
Windows 对每个驱动器都有当前目录的概念.因此,"c:sourcedir"
表示当前 C: 目录中的sourcedir",您需要指定一个绝对目录.
其中任何一个都应该工作并给出相同的结果,但我目前没有启动 Windows VM 来仔细检查:
"c:/sourcedir"os.path.join("/", "c:", "sourcedir")os.path.join("c:/", "sourcedir")
I am trying to learn python and am making a program that will output a script. I want to use os.path.join, but am pretty confused. According to the docs if I say:
os.path.join('c:', 'sourcedir')
I get "C:sourcedir"
. According to the docs, this is normal, right?
But when I use the copytree command, Python will output it the desired way, for example:
import shutil
src = os.path.join('c:', 'src')
dst = os.path.join('c:', 'dst')
shutil.copytree(src, dst)
Here is the error code I get:
WindowsError: [Error 3] The system cannot find the path specified: 'C:src/*.*'
If I wrap the os.path.join
with os.path.normpath
I get the same error.
If this os.path.join
can't be used this way, then I am confused as to its purpose.
According to the pages suggested by Stack Overflow, slashes should not be used in join—that is correct, I assume?
Windows has a concept of current directory for each drive. Because of that, "c:sourcedir"
means "sourcedir" inside the current C: directory, and you'll need to specify an absolute directory.
Any of these should work and give the same result, but I don't have a Windows VM fired up at the moment to double check:
"c:/sourcedir"
os.path.join("/", "c:", "sourcedir")
os.path.join("c:/", "sourcedir")
这篇关于Windows 上的 Python os.path.join的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!