Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inverting path in string with escaped spaces

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

like image 517
Gala Avatar asked Feb 24 '17 22:02

Gala


People also ask

How do you escape a space in a string in Python?

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.

How do you break a path in Python?

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.

What is OS path Normpath?

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.

What is the value of path split?

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 .


2 Answers

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.

like image 170
lmiguelvargasf Avatar answered Sep 30 '22 01:09

lmiguelvargasf


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(' ','\ ')
like image 25
Edd Saunders Avatar answered Sep 29 '22 23:09

Edd Saunders