I want to convert a unix file path, which is in forward-slash format, to a windows file path, which is in backward-slash format. I tried both os.path.join() and os.path.normpath() but both of them seems to add double backwards slash to the result. For example, if I use os.path.normpath('static/css/reset.css')
, the result is 'static\\css\\reset.css'
instead of static\css\reset.css
. And 'static/css/reset.css'.replace('/','\\')
gives me the same result as os.path.normpath
. Is there any way to just get a single-backward-slash-delimited string format?
By the way, I'm using Python2.7 on 64-bit Windows 7.
'static\\css\\reset.css'
is the representation of the string r'static\css\reset.css'
.
The double backsalsh indicates escaping of the backslash - in string literals it has a meaning of "do something special with the next character", which you don't want here.
>>> print('static\\css\\reset.css')
static\css\reset.css
I'm going to expand on on Elzar's correct answer and your comment. What might have gotten you confused and is left unsaid in the previous answers is that there is a difference between the Python string, as you provide it in the source code, and as the python console and IDEs show it to you, the developer, and the way the string is printed, i.e. displayed to the user:
>>> s = 'c:\\directory\\file.txt'
>>> s
'c:\\directory\\file.txt' <-- if you ask for the value, you will see double slashes
>>> print s
c:\directory\file.txt <-- if you print the string, the user will see single slashes
I think the reason you you're getting "The system cannot find the path specified." is because you manually copy to clipboard and paste something from the Python console/IDE (also supported by the fact that your path is shown in quotes in your question).
To add to the confusion, you will sometimes get away with single quotes. Only some slash-character combinations have a special meaning (see Python documentation), e.g. '\n'
for a new line and others don't, e.g. '\s'
, which just prints as \s
.
As a side note, the reason for escaped characters is that they are a convenient way for Python/the computer in general to communicate to the programmer what special characters there are in the text. This way, for example, there's no ambiguity between '\t'
(tab character) and ' '
(a number of spaces), unprintable/some control characters can actually be seen, etc.
static\\css\\reset.css
is being shown because "\\" represents "\". If you use this filepath it will be interpreted as 'static\css\reset.css'.
as a check in the interactive shell
>>> list('static\\css\\reset.css')
gives:
['s', 't', 'a', 't', 'i', 'c', '\\', 'c', 's', 's', '\\', 'r', 'e', 's', 'e', 't', '.', 'c', 's', 's']
"\\" will be shown as a single character.
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