简体   繁体   中英

How to open a file in pandas

Having difficulty opening a csv file in pandas, I have tried:

data = pd.read_csv("/home/me/Programming/data/sample.csv")

That did not work, so I tried:

import os
cwd = os.getcwd()

data = pd.read_csv(cwd + "sample.csv")

and that doesn't work either, just says that file does not exist, but it's there in the file manager clear as day.

os.getcwd() return the current working directory without trailing path separtor.

You should use os.path.join instead of + to correctly join paths:

import os

cwd = os.getcwd()
data = pd.read_csv(os.path.join(cwd, 'sample.csv'))

BTW, there's no need to specify full path of current working directory; just specify sample.csv should be enough:

data = pd.read_csv("sample.csv")

Make sure the file sample.csv is in the current working directory.

Instead of writing the whole path you can make a folder named for example "CSV reader" and then save the python file in the same location either inside or outside the file "CSV reader". If you save the file inside the "CSV reader" folder then the code will be:-

import pandas as pd
pd.read_csv("sample.csv")

If you save the python file outside the folder then the code would look like:-

import pandas as pd
pd.read_csv("CSV reader/sample.csv")

And the work gets easier now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM