Visual Studio Code Python refuses to write to file - python

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?

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)

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)

Related

Python: Json file become empty

Here is my code of accessing&editing the file:
def edit_default_settings(self, setting_type, value):
with open("cam_settings.json", "r") as f:
cam_settings = json.load(f)
cam_settings[setting_type] = value
with open("cam_settings.json", 'w') as f:
json.dump(cam_settings, f, indent=4)
I use It in a program that runs for several hours in a day, and once in a ~week I'm noticing, that cam_settings.json file becoming empty (literally empty, the file explorer shows 0 bytes), but can't imagine how that is possible
Would be glad to hear some comments on what could go wrong
I can't see any issues with the code itself, but there can be an issue with the execution environment. Are you running the code in a multi-threaded environment or running multiple instances of the same program at once?
This situation can arise if this code is executed parallelly and multiple threads/processes try to access the file at the same time. Try logging each time the function was executed and if the function was executed successfully. Try exception handlers and error logging.
If this is a problem, using buffers or singleton pattern can solve the issue.
As #Chels said, the file is truncated when it's opened with 'w'. That doesn't explain why it stays that way; I can only imagine that happening if your code crashed. Maybe you need to check logs for code crashes (or change how your code is run so that crash reasons get logged, if they aren't).
But there's a way to make this process safer in case of crashes. Write to a separate file and then replace the old file with the new file, only after the new file is fully written. You can use os.replace() for this. You could do this simply with a differently-named file:
with open(".cam_settings.json.tmp", 'w') as f:
json.dump(cam_settings, f, indent=4)
os.replace(".cam_settings.json.tmp", "cam_settings.json")
Or you could use a temporary file from the tempfile module.
When openning a file with the "w" parameter, everytime you will write to it, the content of the file will be erased. (You will actually replace what's written already).
Not sure if this is what you are looking for, but could be one of the reasons why "cam_settings.json" becomes empty after the call of open("cam_settings.json", 'w')!
In such a case, to append some text, use the "a" parameter, as:
open("cam_settings.json", 'a')

How to run 2 files(.py) concurrently and update the variable to another file?

My definite goal is to update the real-time value to Matlab(simulink) from python to apply control system.
With separated processes, I get the real-time updating value.
The value type is an integer.
I want to pass this updating value to Matlab workspace.
So I tried using the command in Matlab workspace : pyrunfile('A.py')
However,
As you see this link, 10th line of "Limitations to Python Support",
https://fr.mathworks.com/help/matlab/matlab_external/limitations-to-python-support.html
Matlab doesn't support multiprocessing.
In other words, if I try to run the python file from Matlab workspace,
it doesn't work.
But multiprocessing is requisite for my work. (not working with multithread)
So my idea :
Run the file A.py which contains multiprocessing.
under A.py is still running, I pass the desired updating value to another file B.py with loop .
Export this value to Matlab workspace.
Matlab workspace -> simulink
Firstly , I would like to know whether it sounds feasible or not.
if not, I would like to have some other workflow suggestion.
summary :
python -> matlab is not possible because of multiprocessing.
python -> ?? -> matlab , is there any other method?
I'm not sure if this is the most efficient way, but you could write the variable to a file and read it from the other file.
#Read file
with open("file.txt", "r") as txt_file:
return txt_file.readlines()
#Open file
txt_file = open("file.txt", "w")
txt_file.write(var)
txt_file.close()
You can pass the values like that. I'm not sure how to do the rest, but i hope this helps
Also just make 2 instances of the command line, and run the files seperately to run both of them

Python not creating simple txt file by using "write"

I wrote this simple code and no text file was created. I also tried to create it manually in the same folder and append something on and that also didn't work.
employee_file = open("employees.txt" , "w")
employee_file.write("toby human resources")
employee_file.close()
You should really put the code in the question. After some time the image will probably be deleted and many people won't be able to benefit from your question.
Try the following code:
import os
print (os.getcwd())
employee_file = open("employees.txt" , "w")
employee_file.write("toby human resources")
employee_file.close()
It should print the current working directory, where the file should be saved.
Firstly - your code is correct.
Secondly - why not use "built-in" statements (which closes the file so we don't have take care of it)
with open('employees.txt','w') as file:
file.write("some data")
# do sth else ...
and we don't have to close the file here.

Write Python List to file - works on friends computer but not mine

I've written a program in which I need 3 arrays (lists) to write to a txt file. When I run the code on my computer, the txt file is empty. I sent it to a friend, who ran it and the program populated the txt file on his computer.
I have next to no experience coding and need the txt file for a homework assignment.
Note: It did run earlier today on my computer, although one of the arrays did not write to the file. However, when I ran it again later (after adding additional print statements earlier in the code for error checking), it again wasn't writing to the txt file. What could cause this type of behavior? My code for writing to the txt file is as follows:
import csv
.....
MyFile = open('BattSim.txt', 'w')
wr = csv.writer(MyFile)
wr.writerow(RedArmy)
wr.writerow(BlueArmy)
wr.writerow(BattleTime)
MyFile.close
Did you run this in an interactive interpreter (or in a non-CPython interpreter or otherwise crash in some weird way)? If so, the problem is that you didn't actually flush/close the file; you referenced the close method without calling it. You wanted MyFile.close() (with parens to call).
Alternatively, you use a with statement to get guaranteed close behavior (even if an exception is thrown midway):
import csv
.....
# Use with statement to autoclose, and newline='' to follow csv module rules
with open('BattSim.txt', 'w', newline='') as MyFile:
wr = csv.writer(MyFile)
wr.writerow(RedArmy)
wr.writerow(BlueArmy)
wr.writerow(BattleTime)

Python's readline() function seeming not to work?

for some reason the readline() function in my following code seems to print nothing.
fileName = input()
fileName += ".txt"
fileA = open(fileName, 'a+')
print("Opened", fileA.name)
line = fileA.readline()
print(line)
fileA.close()
I'm using PyCharm, and I've been attempting to access 'file.txt' which is located inside my only PyCharm project folder. It contains the following:
Opened file!!
I have no idea what is wrong, and I can't find any relevant information for my problem whatsoever. Any help is appreciated.
Because you opened the file in a+ mode, the file pointer starts at the end of the file. After all, that is where you would normally append text.
If you want to read from the top, you need to place fileA.seek(0) just before you call readline:
fileA.seek(0)
line = fileA.readline()
Doing so sets the pointer to the top of the file.
Note: After reading the comments, it appears that you only need to do this if you are running a Windows machine. Those using a *nix system should not have this problem.

Categories