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

前端 未结 3 563
梦毁少年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:59

    • This solution by Denziloe does a perfect job of explaining why r may precede a path string.
      • r'C:\Users\username' works
      • r'C:\Users\username\' does not, because the trailing \ escapes the '.
        • r'C:\Users\username\' + file, where file = 'test.csv' also won't work
        • Results in SyntaxError: EOL while scanning string literal
    • pandas methods that will read a file, such as pandas.read_csv will accept a str or a pathlib object for a file path.
    • If you need to iterate through a list a file names you can add them with an f-string as well.
      • num = 6, f'I have {num} files' interprets as 'I have 6 files', is an example of using an f-string.
    import pandas as pd
    
    files = ['test1.csv', 'test2.csv', 'test3.csv']
    
    df_list = list()
    for file in files:
        df_list.append(pd.read_csv(rf'C:\Users\username\{file}'))  # path with f-string
    
    df = pd.concat(df_list)
    

提交回复
热议问题