0

I'm having an incomprehensible error in my code. os.path.join will work with all paths I try, except those started with t after 'RC4'. Here is an example:

>>> os.path.join('RC4\static\posts', '0.png')
'RC4\\static\\posts\\0.png'
>>> os.path.join('RC4\templates\posts', '0.png')
'RC4\templates\\posts\\0.png'

If I split the first string, it works:

>>> os.path.join('RC4', 'templates\posts', '0.png')
'RC4\\templates\\posts\\0.png'
M7kra
  • 51
  • 7
  • 1
    Does this answer your question? [Windows path in Python](https://stackoverflow.com/questions/2953834/windows-path-in-python) – mkrieger1 Jul 02 '21 at 14:32
  • 1
    More specifically, https://stackoverflow.com/questions/19065115/python-windows-path-slash – mkrieger1 Jul 02 '21 at 14:33
  • Also if you use a forward slash, it will work on Windows, Linux, MacOS. and you can use forward slash to join paths instead of os.path.join – AmaanK Jul 02 '21 at 14:34

3 Answers3

3

\t has a special meaning of TAB character (similarly to \n and other "escape" characters). That's why you're discouraged to manually use slashes in your path string.

You better use Path class with / operator

from pathlib import Path
posts_path = Path('RC4') / 'templates' / 'posts'
img_path = posts_path / '0.png'
Alexey S. Larionov
  • 6,555
  • 1
  • 18
  • 37
1

\t is a tab char sequence. Use raw strings to avoid these issues:

os.path.join(r'RC4\templates\posts', '0.png')
bereal
  • 32,519
  • 6
  • 58
  • 104
1

That is because '\t` is a special character representing a Tab (2 or 4 spaces). To avoid it being interpreted in that way, you can escape it using a backslash, like so

os.path.join('RC4\\templates\posts', '0.png')
>>> 'RC4\\templates\\posts\\0.png'

Although, according to xcodz-dot (comment), in a future version of python, you should escape the slash before posts as well, because an error will be raised otherwise, which also works in python 3.8.6:

os.path.join('RC4\\templates\\posts', '0.png')
>> 'RC4\\templates\\posts\\0.png'

Alternatively, you can place an 'r' in front of the string:

os.path.join(r'RC4\templates\posts', '0.png')
>> 'RC4\\templates\\posts\\0.png'
Stryder
  • 848
  • 6
  • 9