Python write() method and close() function not working with latest version of Visual Studio Code. Code works with Python 3.8.5 Shell

Viewed 99

Awhile ago my friend installed Visual Studio Code (along with the python extension) and it's been great so far until I started learning about File Input and Output. My strings are not saving to the desired .txt file using the write() method and using the close() function at the end. No errors are detected by the computer. The .py and the .txt files are in the same folder. Using the flush() method before the close() function did not work either.

The same code successfully writes to the .txt file with no issues if using the default Python 3.8.5 Shell instead of the latest version of Visual Studio Code. Googling for the issue have yielded no results so far. I'm not even sure what keywords should I be using to look for an answer. I'm using Windows 10 Pro Edition.

var_1 = 123
outputFile = open("outputFile.txt", "w")

outputFile.write(str(var_1))

#outputFile.flush() #tried using flush but didn't do anything

outputFile.close()
2 Answers

Hi try add the exact address of the file

File = open("C:\...\yourfilename","r")
In_file = File.read()
File.close()

Visual studio looks for the file in its exe directory

You should mention the full path location when you open the file.

Your code will now work.

var_1 = 123
outputFile = open(r"C:\....\outputFile.txt", "w")

outputFile.write(str(var_1))

#outputFile.flush() #tried using flush but didn't do anything

outputFile.close()
Related