0

File not found error occurs when reading a file as relative path in Visual Studio Code. The file is currently in the same folder as the python script. The same script is read successfully by running it in the Visual Studio.

How can i fix it so It can be read a file as relative path in Visual Studio Code?

Here my python script:

import numpy as np
file_name = 'file.csv'
xy = np.loadtxt(file_name, delimiter=',') # File not found error occured in Visual Studio Code

My OS is Windows.

Ha. Huynh
  • 1,772
  • 11
  • 27
Hyunjin-Kim
  • 159
  • 1
  • 3
  • 14

1 Answers1

0

It is always safe to use the os module for file-paths. The following code prints the current directory and the complete path of the file.csv if it exists in that directory.

import os
cwd = os.getcwd()  # get current working dir: C:\\Users\\%USERPROFILE%\\Desktop
print("My current working directory is: {} ".format(cwd))
#search if the file exists in this directory
for file in os.listdir(cwd):
    if file.startswith("file"):
        print("File \"{}\" is located at \"{}\"".format(file, os.path.join(cwd, file)))

If the file is found in the directory, use the complete path and store it in a variable as a raw string or using os.path.join(). Eg.:

file_name = r"C:\Users\%USERPROFILE%\Desktop\file.csv" #raw string

or

file_name = os.path.join(cwd, "file.csv") #join current working directory with the file.csv

Both will show the complete path as C:\\Users\\%USERPROFILE%\\Desktop\\file.csv.

To print all csv files (with their paths) in the directory, use file.endswith(".csv").

amanb
  • 5,276
  • 3
  • 19
  • 38