-1

In VS Code I have a folder defined as my workspace (e.g.: "/Users/xxxx/Documents/900. PYTHON/# VS Code/Workspace/". I had there a file with Python code (main.py) which was creating and reading the file in the same folder. Name of the file which was created is: "exercise_register.csv"

I created a sub-folder "(...)/Workspace/workouts/" where I moved both the "main.py" file with code and "exercise_register.csv" file.

Now I get and error running the code:

Exception has occurred: FileNotFoundError
[Errno 2] No such file or directory: 'exercise_register.csv'
  File "/Users/xxxx/Documents/900. PYTHON/# VS Code/Workspace/workouts/main.py", line 51, in review_register
    with open("exercise_register.csv", "r") as file:
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

When I use the below code, Python creates new file in the previous folder, not in the "(...)/workouts/" folder, in which the "main.py" file was moved to.

    with open("exercise_register.csv", "w") as file:
        for line in data:
            file.write(line)

Any suggestions how to solve this?

I expected to have the file opened from the same folder where my "exercise.py" file is stored.

I'm adding a picture showing the folder structure to visualise my case:

folder structure

PLR06157
  • 3
  • 3
  • 1
    It is not clear and very confusing which files you are talking about. I think exercise.py is located in (...)/workspace/workouts directory. Please consider providing some sort of file structure for us to understand what is the problem. – InfoDaneMent Mar 12 '23 at 10:23
  • Also, which file contains the code that you mentioned which seems to write to a csv file? – InfoDaneMent Mar 12 '23 at 10:24
  • 1
    A relative path like `"exercise_register.csv"` is interpreted relative to the OS's working directory, which you can verify using `print(os.getcwd())`. The starting value of that directory depends on how the Python interpreter was started - in VSCode it's likely to be the workspace directory. Python does **not** attempt to interpret relative paths relative to the .py file where they are used. – slothrop Mar 12 '23 at 11:54
  • 1
    See: https://stackoverflow.com/questions/40416072/reading-a-file-using-a-relative-path-in-a-python-project – slothrop Mar 12 '23 at 17:55
  • I've updated the description and added a picture to visualise the problem. Thanks @slothrop for sharing the link to similar issue. I'll try to go with that one. – PLR06157 Mar 14 '23 at 10:23

1 Answers1

0

This is caused by vscode using workspace as root floder.

This will lead to a problem. When you use the os.getcwd() method in the deep directory of the workspace, you will still get the workspace directory.

You can open your settings and search Python > Terminal: Execute In File Dir then check it.

enter image description here

You can also use Debug mode and add the following to your launch.json:

"cwd": "${fileDirname}"
MingJie-MSFT
  • 5,569
  • 1
  • 2
  • 13