Why does this program only work when run without debugging in Visual Studio Code?

Question:

Debugging turned out not to be a problem. The file was running in a folder above its own folder so using a relative file location fixed the problem. Still, the fact that it would not run in its own folder is perplexing.

When run without debugging, it works perfectly fine but when run with debugging, there is an error message: Exception has occurred: FileNotFoundError
[Errno 2] No such file or directory: ‘piratein.txt’

input = open("piratein.txt")

distances = (input.readlines())
l = int(distances[0])
x = int(distances[1])
y = int(distances[2])

if x+y<l:
    write = str(x+y)

elif x+y>l:
    write = str((l-x)+(l-y))

#creates and opens an output file for writing
output = open("pirateout.txt", "w")
output.write(write)

#the input file is only 3 lines, each with a single integer
#the path of the input file is "CODINGVisualStudioCodeInformatics OlympiadAIO_PRACTICEpiratein.txt"
#and the python file is in the same folder as the input file
Asked By: Aaron

||

Answers:

double-check that the directory that you are running the python file from,(as seen in the terminal), is also where pirateout.txt is stored. You can use a combination of ‘ls’ and ‘cd ‘ in the command line to navigate to where it is

Answered By: rohan

In launch.json, there are settings about cwd, which specifies the search range of files during debugging. Please put the file piratein.txt in this folder.

enter image description here

Example1:

workspace
-src
--test
---test.py
-helloworld.txt

enter image description here

Example2:

workspace
-src
--test
---test.py
---helloworld.txt

enter image description here

Answered By: MingJie-MSFT
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.