0

I am trying to read data from a csv file (in the same folder as my main.py) but it seems that Visual Studio Code doesn't understand the project folder or something of the sort

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

Here is my code

import numpy as np
import pandas as pd


# read data with panda, only the columns that are needed
r_cols = ['user_id', 'movie_id', 'rating']
ratings = pd.read_csv('ratings.csv', sep=';', names=r_cols, usecols=[1, 2, 3], encoding="ISO-8859-1", low_memory=False, header=0)

Adding the full path of the file fixes the problem, and it also works if I add import os with os.chdir in the beginning of the code.

But PyCharm doesn't need the above tweaks in order to run it. So my question remains, is there a VSCode setting that I am missing?

Steven
  • 47
  • 1
  • 6
  • Since you are using a relative path, vscode and pycharm are running the code with different `cwd`. In all likelihood, vscode has a lunch configuration you can tweak to specify the `cwd`. To verify print the result of `os.getcwd()` – Bhaskar Dec 30 '20 at 18:50
  • How are you running the script? I can think of 3 options in VSCode: green run button, debugging, or from the terminal in VS Code. – Jason Cook Dec 30 '20 at 19:11
  • @JasonCook I usually press the run code button on the top right (it's not green for me, the packages could be interfering). Debugging also has the same issue. Running in terminal actually does work fine, but I would rather find an internal setting to fix this globally and permanently. – Steven Dec 30 '20 at 20:02
  • Does this answer you question? https://stackoverflow.com/questions/41471578/visual-studio-code-how-to-add-multiple-paths-to-python-path – Jason Cook Dec 30 '20 at 20:27

4 Answers4

1

I got the same issue and I solved it by doing this:

enter image description here

import pandas as pd

df = pd.read_csv('Pandas/sample.csv')

print(df)
lejlun
  • 4,140
  • 2
  • 15
  • 31
0
import os

def infolder_file( filename ):
    afname = os.path.abspath(__file__)
    current_folder = os.path.dirname(afname)
    uf = os.path.join(current_folder, filename )
    return uf

print( infolder_file( 'anyfilename.txt' )  )
iqmaker
  • 2,162
  • 25
  • 24
0

You can define a constant for the directory at the top of your module that you then use with any files you need to access.

from pathlib import Path

DIRNAME = Path(__file__).parent

def func():
    fn = DIRNAME / 'file.suffix'

Eric Truett
  • 2,970
  • 1
  • 16
  • 21
0

As people mentioned in the comments, we can set the debug path in VSCode, please add the following settings in "launch.json": (It will automatically go to the directory where the file is located before debugging the code)

"cwd": "${fileDirname}",

enter image description here

Jill Cheng
  • 9,179
  • 1
  • 20
  • 25