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.
CodePudding user response:
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')
CodePudding user response:
Find out which is the "current" directory in your IDE or debugger:
import pathlib
current_path = pathlib.Path.cwd()
print(current_path)