os.sep上的Python拆分和后续联接不能正确生成联接字符串



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)

奇怪的是,这似乎是一个功能,而不是一个bug。。。

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

最新更新