Is this always necessary to use r before path declaration in python

Question:

I have often seen syntax like this in python code.

    import os
    os.chdir(r'C:UserstestDesktop')

I was wondering why would I need to give r before the path, I believe it has something to do with ” in the path , Is there any other way to give path instead of using r”

Asked By: Saranya Sridharan

||

Answers:

It makes sure that the backslash doesn’t escape the characters. It’s same as

os.chdir('C:\Users\test\Desktop')
Answered By: Mr.Someone5352

Only when it has escape sequences

print('C:syscatDesktop')

Better to give it as raw type to avoid the glitches or using forward slash.

Answered By: Smart Manoj

‘r’ before string literal make Python parse it as a “raw” string, without escaping.
If you want not to use ‘r’ before string literal, but specify path with single slashes, you can use this notation:

"C:/Users/test/Desktop"

As it would be in unix-pased systems. Windows understand both “” and “/” in file paths, so, using “/” give you ability to avoid ‘r’ letter before the path string.

Also, as it was mentioned, you can specify path with double slashes, but, as I realized, this is not that you wanted:

"C:\Users\test\Desktop"
Answered By: MihanEntalpo

You can use forward slashes in Windows as well, so you dont need raw string literals:

>>> import os
>>> os.stat(r'C:Usersf3kDesktopexcel.vbs')
nt.stat_result(st_mode=33206, st_ino=0L, st_dev=0, st_nlink=0, st_uid=0, st_gid=0, st_size=555L, st_atime=1367585162L, st_mtime=1367586148L, st_ctime=1367585162L)

Same using forward slashes:

>>> os.stat('C:/Users/f3k/Desktop/excel.vbs')
nt.stat_result(st_mode=33206, st_ino=0L, st_dev=0, st_nlink=0, st_uid=0, st_gid=0, st_size=555L, st_atime=1367585162L, st_mtime=1367586148L, st_ctime=1367585162L)

But take care using os.path.join():

>>> os.path.join('C:/Users/f3k/Desktop', 'excel.vbs')
'C:/Users/f3k/Desktop\excel.vbs'
Answered By: Maurice Meyer

As per knowledge, you can use forward slash instead of backward slash and put r on it. If you use a backslash then you have to put r in front of it or you can do a forward slash if you want to.

Example – > You can try this in Jupyter notebook:

f = open(r'F:love.txt', 'r') 

or

f = open('F:/love.txt', 'r')

Both will work fine.

Answered By: Sumit Barua
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.