gpt4 book ai didi

python - 解决 sys.path 和 os.path.join 中的混合斜线问题

转载 作者:行者123 更新时间:2023-12-05 00:24:52 29 4
gpt4 key购买 nike

我需要解决 sys.path 提供的分隔符和 os.path.join 使用的分隔符之间的差异。

我模仿了这个 Esri 方法 ( Techniques for sharing Python scripts ) 使我的脚本可移植。它目前在 Windows 中使用,但最终将在 Linux 服务器上运行;我需要让 Python 确定适当的斜线。

他们的建议是:

# Get the pathname to this script
scriptPath = sys.path[0]

# Get the pathname to the ToolShare folder
toolSharePath = os.path.dirname(scriptPath)

# Now construct pathname to the ToolData folder
toolDataPath = os.path.join(toolSharePath, "ToolData")
print "ToolData folder: " + toolDataPath

但这会输出 ToolData folder: C:/gis\ToolData - 显然,混合斜线是行不通的。

此问题 ( mixed slashes with os.path.join on windows ) 包括解决方案的基本方法:

check your external input (the input you apparently do not control the format of) before putting it in os.path.join. This way you make sure that os.path.join does not make bad decisions based on possibly bad input



但是,我不确定如何确保它可以跨平台工作。如果我使用 .replace("/","\\")sys.path[0]结果,这对 Windows 来说很棒,但是一旦我过渡到 Unix,这是否会导致相同的混合斜杠问题?

最佳答案

如何使用os.path.normpath() ?

>>> import os
>>> os.path.normpath(r'c:\my/path\to/something.py')
'c:\\my\\path\\to\\something.py'

还值得一提的是:Windows 路径 API 并不关心是使用正斜杠还是反斜杠。通常是程序没有正确处理斜线的错误。例如,在python中:
with open(r'c:/path/to/my/file.py') as f:
print f.read()

将工作。

关于python - 解决 sys.path 和 os.path.join 中的混合斜线问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25648256/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com