简体   繁体   中英

Loading CSV into Pandas - no file directory

I need help debugging this code. I am trying to add a csv file to my pandas data frame.

import pandas as pd
df = pd.read_csv ('batting.csv')
print(df)

When I execute this code I am getting this error:

FileNotFoundError: [Errno 2] No such file or directory: 'batting.csv'

I then tried to change the directory using os

os.getcwd()
os.chdir(r"C:\Users\crack\Downloads\excel\batting.csv")

I am now coming across this error:

NotADirectoryError: [WinError 267] The directory name is invalid: 'C:\\Users\\crack\\Downloads\\excel\\batting.csv'

I am new to coding and have been looking for a solution to this error all day.

You could try,

df = pd.read_csv(r"C:\Users\crack\Downloads\excel\batting.csv")

instead of df = pd.read_csv ('batting.csv')

You are on the right track. The working directory is probably not where your file is located.

Try doing the following to see where it is:

print(os.getcwd())

The error you are seeing using os.chdir() is because you have specified a filename not a directory.

You have a few possible solutions:

  1. Specify the full path to your CSV file:

     pd.read_csv(r"C:\Users\crack\Downloads\excel\batting.csv")
  2. Change the working directory to the same folder:

     os.chdir(r"C:\Users\crack\Downloads\excel") pd.read_csv("batting.csv")
  3. If the script and CSV files are in the same folder and you don't want to specify a fixed path:

     os.chdir(os.path.dirname(os.path.abspath(__file__))) pd.read_csv("batting.csv")

    This changes the working directory to be where the script is located. It takes the full script name and uses just the directory part.

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