pandas 使用pandas读取csv文件时需要在路径名之前使用'r'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42654934/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:08:10  来源:igfitidea点击:

Need of using 'r' before path-name while reading a csv file with pandas

pythonpandas

提问by Rishabh

a newbie here. Could someone tell me why do we use an 'r' in some cases before the path name in the following function?:

这里是新手。有人能告诉我为什么在某些情况下我们在以下函数的路径名之前使用 'r' 吗?:

df = pd.read_csv(r"Path_name")

Thanks in advance

提前致谢

回答by Denziloe

In Python, backslash is used to signify special characters.

在 Python 中,反斜杠用于表示特殊字符。

e.g. "hello\nworld" -- the "\n" means a newline. Try printing it.

例如“hello\nworld”——“\n”表示换行。尝试打印它。

Path names on Windows tend to have backslashes in them. But we want them to mean actual backslashes, not special characters.

Windows 上的路径名往往带有反斜杠。但是我们希望它们表示实际的反斜杠,而不是特殊字符。

r stands for "raw" and will cause backslashes in the string to be interpreted as actual backslashes rather than special characters.

r 代表“raw”,会导致字符串中的反斜杠被解释为实际的反斜杠而不是特殊字符。

e.g. r"hello\nworld" literally means the characters "hello\nworld". Again, try printing it.

例如 r"hello\nworld" 字面意思是字符“hello\nworld”。再次尝试打印它。

More info is in the Python docs, it's a good idea to search them for questions like these.

更多信息在 Python 文档中,搜索它们以查找此类问题是个好主意。

https://docs.python.org/3/tutorial/introduction.html#strings

https://docs.python.org/3/tutorial/introduction.html#strings

回答by EdChum

A raw string will handle back slashes in most cases, such as these two examples:

在大多数情况下,原始字符串将处理反斜杠,例如以下两个示例:

In [11]:
r'c:\path'

Out[11]:
'c:\path'

However, if there is a trailing slash then it will break:

但是,如果尾部有斜杠,则它将中断:

In [12]:
r'c:\path\'

  File "<ipython-input-12-9995c7b1654a>", line 1
    r'c:\path\'
               ^
SyntaxError: EOL while scanning string literal

Forward slashes doesn't have this problem:

正斜杠没有这个问题:

In [13]:
r'c:/path/'

Out[13]:
'c:/path/'

The safe and portable method is to use forward slashes always and if building a string for a full path to use os.pathto correctly handle building a path that will work when the code is executed on different operating systems:

安全且可移植的方法是始终使用正斜杠,如果为完整路径构建字符串os.path以正确处理构建在不同操作系统上执行代码时有效的路径:

In [14]:
import os
path = 'c:/'
folder = 'path/'
os.path.join(path, folder)

Out[14]:
'c:/path/'