【问题标题】:Python split and subsequent join on os.sep does not yield properly joint stringos.sep 上的 Python 拆分和后续连接不会产生正确的连接字符串
【发布时间】:2022-10-06 17:21:34
【问题描述】:

Windows 10 上的 python 3.8

我正在尝试创建一个脚本来自动创建一个 .bat 文件来激活正确的环境或当前脚本。为此,我需要进行一些路径操作,本质上包括以下代码:

import os
cwd = os.getcwd()
s = cwd.split(os.sep)
n = os.path.join(*s,\'test.bat\')
print(n)

预期结果:

C:\\\\Data\\\\test.bat

实际结果:

C:Data\\\\test.bat

这缺少驱动器后的 \\ 分隔符。 同样对于更深的文件夹结构,这只会在加入驱动器时出错。这里出了什么问题?

完整代码:

import os

python_file = \'python_file_name.py\'  # file to run
program_name = \'Start Python Program\'  # Name of the resulting BAT file

cwd = os.getcwd()  # directory in which the Python file lives
env = os.environ[\'CONDA_PREFIX\']  # environment name in Conda
act = os.environ[\'CONDA_EXE\'].split(os.sep)[:-1]  # activate.bat lives in the same directory as conda.exe
act = os.path.join(*act,\'activate.bat\')

# Construct the commands

text = f\'\'\'ECHO ON
CD {cwd}
CALL {act} {env}
CALL {python_file}
\'\'\'

with open(f\'{program_name}.bat\', \'w\') as f:
    f.write(text)
    
  • 不要认为你需要拆分,只需os.path.join(cwd, \'test.bat\') 应该可以吗?
  • 为了便于理解,我只展示了简化的代码。我刚刚包含了完整的代码。
  • 这是一种解决方法,但没有回答问题:(os.sep).join([*s]+[\'test.bat\'])
  • 仍然没有答案,但我发现了更多:它仅在拆分列表中的第一项上失败(我可以在其他任何地方插入 \":\" 并且它可以工作)并且仅在单字母驱动器上。我的系统中是否存在这样的驱动器并不重要,但它拒绝将 C:、D:、Y:、Z: 等内容正确连接到第一个位置。

标签: python string path


【解决方案1】:

奇怪的是,这似乎是一个功能,而不是一个错误......

https://docs.python.org/3/library/os.path.html

【讨论】:

    猜你喜欢
    • 2011-04-01
    • 2011-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-02
    • 1970-01-01
    • 2017-08-16
    • 2014-10-27
    相关资源
    最近更新 更多