I need to pass a subtitle path to VLC, it only takes native paths (backslashes on Windows, forward slashes on Unix) and needs space escaping.
Let's say I have a Qt native path with a space in it.
C:/Users/Thinkpad/Downloads/test file.srt
How do I convert it into this:
C:\\Users\\Thinkpad\\Downloads\\test\ file.srt
In Python strings, the backslash "\" is a special character, also called the "escape" character. It is used in representing certain whitespace characters: "\t" is a tab, "\n" is a newline, and "\r" is a carriage return.
path. split() method in Python is used to Split the path name into a pair head and tail. Here, tail is the last path name component and head is everything leading up to that.
os.path. normpath (path) Normalize a pathname by collapsing redundant separators and up-level references so that A//B , A/B/ , A/./B and A/foo/../B all become A/B . This string manipulation may change the meaning of a path that contains symbolic links. On Windows, it converts forward slashes to backward slashes.
path. Split splits PATH immediately following the final slash, separating it into a directory and a base component. The returned values have the property that PATH = DIR + BASE . If there is no slash in PATH , it returns an empty directory and the base is set to PATH .
To handle this problem I strongly suggest using
os.path.normpath('C:/Users/Thinkpad/Downloads/test file.srt')
If you enter all of your filename strings using forward slashes, and then let os.path.normpath(path)
change them to backslashes for you, this way.
Not sure if there is anything in the standard library to handle this, but if it is just slashes and spaces you need a simple string replace will be faster and simpler. i.e.
path = path.replace('/','\\').replace(' ','\ ')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With