1

I am relatively new to python and now have the following problem. Since recently whenever I generate or include a path in a code the \ is replaced by \. Like e.g. when using

os.join

or when using

r'mypat\myfiles\myfile.py'

or

u'mypat\myfiles\myfile.py'

A work around I found for myself so far was using '/' instead of '\' which did the job. But now I want to manually install a package and get the error

path wrong: C:\\Program Files\\Anaconda2\\pkgs\\...

I assume its something in the settings of either on my computer or the basic python settings. Its Window 7 and I tried German and English Language settings with the same result.

horseshoe
  • 1,437
  • 14
  • 42

2 Answers2

2

You have to escape them with an additional slash:

print('mypat\\myfiles\\myfile.py')
lapinkoira
  • 8,320
  • 9
  • 51
  • 94
2

os.path.join() is multi-platform, if used on Windows, it will generate a windows path with \, for linux it will generate a linux path with "/

Linux :

Python 3.6.0 (default, Dec 24 2016, 08:03:08) 
[GCC 6.2.1 20160830] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.path.join("toto", "tutu")
'toto/tutu'
>>> 

Windows :

λ python
Python 3.5.3 (v3.5.3:1880cb95a742, Jan 16 2017, 16:02:32) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.path.join("toto", "tutu")
'toto\\tutu'
>>>

You should never use an hardcoded path in your code. If your software is multi-platform, write path using linux style and then build it using os.path.join, it will be reformated

An other post which could interest you : mixed slashes with os.path.join on windows

Community
  • 1
  • 1
PyNico
  • 695
  • 5
  • 21
  • Thx. So If I want to use a code that uses os (and that I cannot change) on a windows machine, what can I do that its not toto\\tutu but toto\tutu? – horseshoe Feb 02 '17 at 11:04
  • toto\\tutu is valid, toto\tutu is not valid , toto/tutu is valid. I would always use "/". (not sure to understand). If you really want have "\". i would just build my path, then replace "\\" or "/" with "\" – PyNico Feb 02 '17 at 11:07
  • Thanks, I think the link and your comments made it clear to me. I thought the \\ was the problem that the code couldn't find the path but I guess I have to search elsewhere. – horseshoe Feb 02 '17 at 12:03