-2

Opened VS code thru Anaconda3 and when trying to read a csv using pandas

df = pd.read_csv('file.csv') 

My file.csv exists in same directory as my panda.py file but i receive a

FileNotFoundError: [Errno 2] File b'file.csv' does not exist: b'file.csv'

I can physically see the file in the same directory but my terminal says its not. Why is this happening and how can i fix it?

AMC
  • 2,642
  • 7
  • 13
  • 35
  • 1
    Read_csv is looking for the file in the folder where python is installed. Try using the full path – RichieV Aug 04 '20 at 01:09
  • find out what the current directory is when you try to read the CSV file, you can set the `cwd` in the launch.json file – rioV8 Aug 04 '20 at 01:09
  • Here's how to get your path programatically https://stackoverflow.com/a/7166139/6692898 – RichieV Aug 04 '20 at 01:11

3 Answers3

1

${cwd} - the task runner's current working directory on startup.

The default setting of 'cwd' is the "${workspaceFolder}". In VSCode, the relative path depends on the setting parameter 'cwd', unless you use an absolute path. It doesn't care the relative path to your python file, it just cares the relative path to 'cwd'.

So you have two solutions to solve this problem:

First One:

Use the absolute path as you had tried and worked:

df = pd.read_csv(r'C:\Users\First Last\Documents\StatPython\file.csv')

or

df = pd.read_csv('C:\Users\irst Last\Documents\StatPython\file.csv')

Second One:

Take the path relative to default ${cwd}:

df = pd.read_csv('[the path of cwd][some paths]\file.csv')

In this case, seems like you haven't created a project of 'StatPython'. If it is your project name and opened by VSCode your code should be worked.

Steven-MSFT
  • 7,438
  • 1
  • 5
  • 13
0

this is because you are using a DataFrame to read the csv file while the DataFrame module cannot do that. Instead you can try using pandas to do the same operation by importing it using import pandas as pd and to read the file use pd.read_csv('filename.csv')

0

Still not sure why my code in question did not work, but this ended up working.

df = pd.read_csv(r'C:\Users\First Last\Documents\StatPython\file.csv')

Not only did i need the full path but an "r" before it.

  • you need the `r` because you have `\` in your string – rioV8 Aug 04 '20 at 03:43
  • Both string and bytes literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and treat backslashes as literal characters. – Steven-MSFT Aug 04 '20 at 06:09