Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix forward slash issue in path on windows in python?

I have developed an application in python and pyside. I have developed it on linux machine. Now I want to deploy it on windows machine. Here problem is path. In linux forward slash(/) used as separator but windows uses backward slash(\) as separator.

So, on windows all paths not work. There are several paths in application(for stylesheet, images, log etc.)

Its difficult to change all paths as most of paths are hard code like:

 rootPath()+'/static/images/add.png' #rootPath return os.path...

Example:

 colorPickerBtnStyle = 'background:url(' + rootPath() + '/static/images/color_icon.png);background-repeat: no-repeat;background-position:center center;'

Is there any work around for this problem.

like image 303
anils Avatar asked May 26 '12 13:05

anils


People also ask

How do you get rid of the forward slash in Python?

replace() method to remove the forward slashes from a string, e.g. new_string = string. replace('/', '') . The str. replace() method will remove the forward slashes from the string by replacing them with empty strings.

How do I change the path slash in Python?

Programming languages, such as Python, treat a backslash (\) as an escape character. For instance, \n represents a line feed, and \t represents a tab. When specifying a path, a forward slash (/) can be used in place of a backslash. Two backslashes can be used instead of one to avoid a syntax error.

Can I use forward slash in Windows path?

You can use forward slashes ( / ) instead of backward slashes ( \ ) on Windows (as is the case with Linux® and UNIX). If you use backward-slashes, the file name on Windows might be treated as a relative-path instead of an absolute-path.

Why is Python adding backslashes to string?

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. Conversely, prefixing a special character with "\" turns it into an ordinary character.


2 Answers

os.path.join() will use the right kind of slash on the right platform.

like image 77
Thomas Avatar answered Oct 14 '22 17:10

Thomas


use os.sep instead of explicitly writing the slashes.

like image 26
user1413824 Avatar answered Oct 14 '22 18:10

user1413824