pythonos.path

Python setting a extra "/" or "\" to os.join for file path without doing a +


I have a some code to code to a file path, take that as the executable point aka CD command in shell and then execute the command for that directory part.

Normally, I use OS.PATH.JOIN to create file path but I noticed it still creates an invalid file path because there seems to be / missing initialising it.

So how to solve this I did the following

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

But is there not a way that I do not have add that / tot my string contention?

Of note to hide some context and to safeguard some company info of what I am using it for some data is classified and replaced with flavor text.

file_path = "/" + os.path.join("sys","bus","w1","devices","Other variable")
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

Technically, I should do "/sys" in my join path but I am asking to be curious because there is difference in windows and Linux. If I do this in theory, it should not work for Windows. Yes I know I cannot use these commands in Windows because windows does not have I2C wire1. It is purely theoretical if I want to execute a similar command where such a situation shows itself.


Solution

  • You can try using the os separator (os.sep), this way it will work with both Linux and Windows paths.

    Example for Windows:

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

    The resulted path can be used with os.chdir(file_path) if the folders already exist.