1

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.

1
  • 1
    Indeed, ...\batting.csv is not a directory - it's a file. You could try pd.read_csv(r"C:\Users\crack\Downloads\excel\batting.csv") Commented May 7, 2022 at 21:16

2 Answers 2

1

You could try ,

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

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.