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
# 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')
import pandas as pd
df = pd.read_csv('C:/data_folder/data.csv')
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}")
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)
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())