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

I work with pandas and you need to read some csv files, the structure is something like this.

folder / folder2 / scripts_folder / script.py

folder / folder2 / data_folder / data.csv

how can i open the data.csv file from script in scripts_folder?

I tried this:

absolute_path = os.path.abspath(os.path.dirname('data.csv')) pandas.read_csv(absolute_path + '/data.csv') 

I get this error:

 File folder/folder2/data_folder/data.csv does not exist 
+6
source share
4 answers

Try

 import pandas as pd pd.read_csv("../data_folder/data.csv") 
+12
source

Pandas will start to look where your current python file is located. Therefore, you can go from the current directory to where your data is located on ".." For example:

 pd.read_csv('../../../data_folder/data.csv') 

Will go 3 levels up, and then to the data folder (it is assumed that there) Or

 pd.read_csv('data_folder/data.csv') 

if your data_folder folder is in the same directory as your .py file.

+5
source

You can use the __file__ attribute:

 import os import pandas as pd df = pd.read_csv(os.path.join(os.path.dirname(__file__), "../data_folder/data.csv")) 
+1
source
 # 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
source

All Articles