How to open my files in data_folder with pandas using relative path?

前端 未结 11 2333
庸人自扰
庸人自扰 2020-12-22 23:40

I\'m working with pandas and need to read some csv files, the structure is something like this:

folder/folder2/scripts_folder/script.py

folder/fol

相关标签:
11条回答
  • 2020-12-23 00:34
    # script.py
    current_file = os.path.abspath(os.path.dirname(__file__)) #older/folder2/scripts_folder
    
    #csv_filename
    csv_filename = os.path.join(current_file, '../data_folder/data.csv')
    
    0 讨论(0)
  • 2020-12-23 00:36
    import pandas as pd
    df = pd.read_csv('C:/data_folder/data.csv')
    
    0 讨论(0)
  • 2020-12-23 00:41

    Keeping things tidy with f-strings:

    import os
    import pandas as pd
    
    data_files = '../data_folder/'
    csv_name = 'data.csv'
    
    pd.read_csv(f"{data_files}{csv_name}")
    
    0 讨论(0)
  • 2020-12-23 00:43

    This link here answers it. Reading file using relative path in python project

    Basically using Path from pathlib you'll do the following in script.py

    from pathlib import Path
    path = Path(__file__).parent / "../data_folder/data.csv"
    pd.read_csv(path)
    
    0 讨论(0)
  • With python or pandas when you use read_csv or pd.read_csv, both of them look into current working directory, by default where the python process have started. So you need to use os module to chdir() and take it from there.

    import pandas as pd 
    import os
    print(os.getcwd())
    os.chdir("D:/01Coding/Python/data_sets/myowndata")
    print(os.getcwd())
    df = pd.read_csv('data.csv',nrows=10)
    print(df.head())
    
    0 讨论(0)
提交回复
热议问题