pythoncsvvisual-studio-codefile-readproject-folder

VS Code: Is there a way to read a csv file without needing specification of the full path?


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?


Solution

  • 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