max
max

Reputation: 4521

Read CSV with Pandas from subdirectory on Windows and UNIX

I am writing a Python script that I need to run on Windows and UNIX systems.

I have two folders, let's call them 'Main' and 'Data'. 'Main' contains 'Data' and my script, and 'Data' contains my data in the form of CSV files.

'Main' --> 'Data' ---> data1.csv, data2.csv....

Currently my code below works if I keep the CSV files in 'Main'. How can I get it to work on both Windows and UNIX, keeping the CSV files in 'Data', if the path naming conventions are different?

Here is the code I am running

import pandas as pd
myfile = "data1.csv" 
df = pd.read_csv(myfile,sep=',')

Upvotes: 2

Views: 5959

Answers (1)

KPLauritzen
KPLauritzen

Reputation: 1869

Python 3 has a library to handle paths (https://docs.python.org/3.6/library/pathlib.html).

So in both cases you would do

from pathlib import Path
import pandas as pd
root = Path('main', 'data')
df = pd.read_csv(root / 'data1.csv')

Upvotes: 4

Related Questions