Home > Mobile >  Loading CSV into Pandas - no file directory
Loading CSV into Pandas - no file directory

Time:05-09

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.

CodePudding user response:

You could try ,

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

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

CodePudding user response:

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 your 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.

  • Related