简体   繁体   English

这是否总是需要在 python 中的路径声明之前使用 r

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

I have often seen syntax like this in python code.我经常在 python 代码中看到这样的语法。

    import os
    os.chdir(r'C:\Users\test\Desktop')

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''我想知道为什么我需要在路径前给出 r,我相信它与路径中的'\'有关,有没有其他方法可以给出路径而不是使用 r''

'r' before string literal make Python parse it as a "raw" string, without escaping. 字符串文字前的'r'使Python将其解析为“原始”字符串,而不进行转义。
If you want not to use 'r' before string literal, but specify path with single slashes, you can use this notation: 如果不想在字符串文字前使用'r',而是使用单斜杠指定路径,则可以使用以下表示法:

"C:/Users/test/Desktop"

As it would be in unix-pased systems. 就像在Unix粘贴系统中一样。 Windows understand both "\\" and "/" in file paths, so, using "/" give you ability to avoid 'r' letter before the path string. Windows理解文件路径中的“ \\”和“ /”,因此,使用“ /”可以避免在路径字符串之前使用“ r”字母。

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"

It makes sure that the backslash doesn't escape the characters. 确保反斜杠不会转义字符。 It's same as 一样

os.chdir('C:\\Users\\test\\Desktop')

Only when it has escape sequences 仅当它具有转义序列时

print('C:\sys\cat\Desktop')

Better to give it as raw type to avoid the glitches or using forward slash. 最好将其作为原始类型使用,以避免出现小故障或使用正斜杠。

You can use forward slashes in Windows as well, so you dont need raw string literals: 您也可以在Windows中使用正斜杠,因此不需要原始字符串文字:

>>> import os
>>> os.stat(r'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)

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():

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

As per knowledge, you can use forward slash instead of backward slash and put r on it.根据知识,您可以使用正斜杠而不是反斜杠并将r放在上面。 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.如果您使用反斜杠,则必须在其前面加上r ,或者如果您愿意,可以使用正斜杠。

Example - > You can try this in Jupyter notebook:示例 -> 您可以在 Jupyter notebook 中尝试这个:

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

or或者

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

Both will work fine.两者都可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM