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

前端 未结 3 564
梦毁少年i
梦毁少年i 2020-11-27 19:58

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

df = pd.read_csv(r\"Path_name\")
<         


        
3条回答
  •  南方客
    南方客 (楼主)
    2020-11-27 20:50

    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 "", 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.path to correctly handle building a path that will work when the code is executed on different operating systems:

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

提交回复
热议问题