Reputation: 31
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'
Upvotes: 0
Views: 919
Reputation: 880
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'
Upvotes: 1
Reputation: 7927
\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'
Upvotes: 3
Reputation: 34282
\t
is a tab char sequence. Use raw strings to avoid these issues:
os.path.join(r'RC4\templates\posts', '0.png')
Upvotes: 1