0

I currently have the following files in the same folder/directory:

test.py,

text = open("info.txt", 'r')
print(text.readline())

and info.txt.

Hello, StackOverflow

When I run

python3 test.py

It works, and prints accordingly "Hello, StackOverflow", but when I press F5 to debug it in VSCode, it produces the following error:

[Errno 2] No such file or directory: 'info.txt'
  File "/Users/*****/test/test.py", line 1, in <module>
    text = open("info.txt", 'r')

I suspect it is a problem with the way I configured my Debugger. My current launch.json file:

{
    "version": "0.2.0",
    "configurations": [
    
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
        }
    ]
}

Can anyone lend a hand? I'm not too sure how to configure JSON files, and the settings listed on the VSCode site aren't very helpful.

If I need to provide further information, please say, because I'm not sure if this is the problem.

3
  • 2
    VSCode -- how to set working directory for debug Commented Dec 3, 2021 at 19:56
  • 1
    It's the first hit when googling "visual studio code python debug working directory" Commented Dec 3, 2021 at 19:59
  • I wasn't aware there was a term for it. Thank you. Commented Dec 3, 2021 at 20:02

1 Answer 1

-1

The issue is that when you create a file with open('myfile.txt','r') you use the 'r' flag, that indicates that the file will only be read, so if the file do not exists the error will continue to appear

In order to solve this you must use the 'w' flag instead of 'r' so it will create the file and open it. If the error still persist you might wanna check the path given to the function.

If you are shure that the file exists and do not want to overwrite it you can try this

try:
    text = open('file.txt', 'r')
except FileNotFoundError:
    text = open('file.txt','w')
Sign up to request clarification or add additional context in comments.

2 Comments

This is completely irrelevant because I'm trying to read from the file. Why would I use 'w'?
This isn't completely irrelevant - opening a file for writing will create it if it didn't exist. However, it's not what you were looking for.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.