Python 设置一个额外的“/”或“\”到 os.join 文件路径而不做 + [重复]

问题描述 投票:0回答:1

我有一些代码可以编码到文件路径,将其作为 shell 中的可执行点 aka CD 命令,然后执行该目录部分的命令。

通常,我使用 OS.PATH.JOIN 创建文件路径,但我注意到它仍然创建了一个无效的文件路径,因为似乎/缺少初始化它。

那么如何解决这个问题我做了以下

file_path = "/" + os.path.join("sys","bus","w1","devices","Devicename")

但是有没有办法让我不添加那个/tot 我的字符串争用?

值得注意的是隐藏一些上下文并保护我正在使用它的一些公司信息,某些数据被分类并替换为风味文本。

file_path = "/" + os.path.join("sys","bus","w1","devices","DeviceSerial Number")
command_txt_file = "txtfile command"
path_to_file = os.path.join(file_path,command_txt_file)
os.chdir(file_path)
Commandvariable = os.system("cat Commandvariable")

with open(path_to_file) as f:
    contents = f.read()
reading = float(contents)
CommandVariable = Commandconvertfucntion(reading)
return CommandVariable

从技术上讲,我应该在我的加入路径中做“/sys”,但我想好奇,因为 Windows 和 Linux 是不同的。如果我在理论上这样做,它不应该适用于 Windows。 是的,我知道我不能在 Windows 中使用这些命令,因为 Windows 没有 I2C wire1。如果我想在出现这种情况的地方执行类似的命令,那纯粹是理论上的。

python os.path
1个回答
1
投票

您可以尝试使用 os 分隔符 (

os.sep
),这样它可以在 Linux 和 Windows 路径下工作。

Windows 示例:

import os
>>> f = os.path.join(os.sep,'something','subfolder')
>>> f
'\\something\\subfolder'
>>> f = os.path.join('something','subfolder')
>>> f
'something\\subfolder'

如果文件夹已经存在,则结果路径可以与

os.chdir(file_path)
一起使用。

© www.soinside.com 2019 - 2024. All rights reserved.