skip to Main Content

I’m trying to have a program output data to a JSON file, but VS code or Python itself seems to have a problem with that. Specifically, I’m trying to output this(Tlist and Slist are lists of integers):

output = {"Time": Tlist, "Space": Slist}
json_data = json.dumps(output, indent=4)
with open("sortsOutput.json", "a") as outfile:
    outfile.write(json_data)

But nothing seems to be happening. SortsOutput.json was never made, and even with a pre-existing SortsOuput.json nothing happened. Heck, this doesn’t even work:

out = open("blah.txt", "w")
out.write("Egg")
out.close()

What might be going wrong for my software for this to happen? I’m using Python v2022.16.1, for the record, and every time the program runs for the first time the command "conda activate base" happens with some error text that doesn’t seem to affect the rest of my program, so is it that? How do I fix that?

2

Answers


  1. out = file.open("blah.txt", "w")

    In your second example, it seems that you don’t need file.. open() is a built-in method of Python.
    You can use out = open("blah.txt", "w") directly.

    At the same time, this problem seems to have nothing to do with vscode.

    I think this problem is more likely due to the path problem. The .json file you executed does not exist in the first level directory under the workspace.

    For example,

    Workspace
     -.vscode
      -sortsOutput.json
     -test.py
    

    You need to use the workspace as the root directory to tell the specific location of python files:

    with open(".vscode/sortsOutput.json", "a") as outfile:
        outfile.write(json_data)
    
    Login or Signup to reply.
  2. I was unable to write file using MS Visual Studio Community (python), in my case it was an encoding issue. I found the solution at: https://peps.python.org/pep-0263/ just put a special comment: # coding=<encoding name> at the first line of the python script

    (in my case: # coding=utf-8)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search