Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python windows path slash [duplicate]

Tags:

python

I am facing a very basic problem using directory path in python script. When I do copy path from the windows explorer, it uses backward slash as path seperator which is causing problem.

>>> x
'D:\testfolder'
>>> print x
D:      estfolder
>>> print os.path.normpath(x)
D:      estfolder
>>> print os.path.abspath(x)
D:\     estfolder
>>> print x.replace('\\','/')
D:      estfolder

Can some one please help me to fix this.

like image 937
sarbjit Avatar asked Sep 28 '13 08:09

sarbjit


People also ask

How do you do a double backslash in Python?

In Python, you use the double slash // operator to perform floor division. This // operator divides the first number by the second number and rounds the result down to the nearest integer (or whole number).

Does Python use backslash or forward slash?

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.

Why should backslashes typically be avoided when writing paths in Python?

This problem arises because the Windows system uses the backslash “\” as a path separator and Linux uses the slash “/”. Unfortunately, since the Windows separator is also the initiator for diverse special characters or escape in Unicode, it obviously confuses everything.


1 Answers

Python interprets a \t in a string as a tab character; hence, "D:\testfolder" will print out with a tab between the : and the e, as you noticed. If you want an actual backslash, you need to escape the backslash by entering it as \\:

>>> x = "D:\\testfolder"
>>> print x
D:\testfolder

However, for cross-platform compatibility, you should probably use os.path.join. I think that Python on Windows will automatically handle forward slashes (/) properly, too.

like image 128
mipadi Avatar answered Oct 17 '22 17:10

mipadi