How to create file in pyscript

Hi,

I am trying to store some results to a txt file, but I got the following error:
f = open(filename, 'w') ^ NameError: name 'open' is not defined

Can anyone please help?
Thank you very much.

1 Like

From the docs (https://hacs-pyscript.readthedocs.io/en/latest/reference.html#avoiding-event-loop-i-o):

Currently the built-in functions that do I/O, such as open, read and write are not supported to avoid I/O in the main event loop, and also to avoid security issues if people share pyscripts. Also, the print function only logs a message, rather than implements the real print features, such as specifying an output file handle. If you want to do file I/O from pyscript, you have two choices:

  • put the code in a separate native Python module, so that functions like open, read and write are available, and call the function in that module from pyscript using task.executor. See Importing for how to set Python’s sys.path to import a local Python module.
  • you could use the os package (which can be imported by setting allow_all_imports) and calling the low-level functions like os.open and os.read using task.executor to wrap every function.
1 Like

@rccoleman Thanks a lot.
I can create files and store data now.

You seem to have the solution to this same problem I have! It is driving me up the wall; I can’t find an example anywhere. I have this:

file = task.executor(os.open, filepath, “w”)

But it generates an error stating it can’t interpret a string as an integer. This must refer to the write (“w”) argument.

My question is: how do I pass this argument to the task executor?

Thanks in advance…

1 Like

any news on this ? I have the same problem :frowning:

1 Like

I’ve had another desperate battle with this, using chatGPT, but my frustration levels are through the roof right now. Why did they make it impossible to write and read a simple text ot JSON file!?! Really annoying…

Sorry, but I give up, at least until my cortisol is at a normal level again.

1 Like

I was having the same problem.

I fixed it by switching from os.open to io.open