How do I open files to read/write in Mojo?
I want to do the equivalent of the following Python code:
How can I do this?
23 Replies
You can use @lukas 's lib for now: https://github.com/lsh/shims
GitHub
GitHub - lsh/shims: Utils for mojo projects
Utils for mojo projects. Contribute to lsh/shims development by creating an account on GitHub.
@sa-code How do you use this repository to read files? The read has code but there's no example usage, so it's hard to understand
The read code has an example at the top of the file
Thanks, will try it out!
@lukas can you give an example on how to write files as well? Thanks a lot!
I haven’t written a wrapper for that yet
I haven’t had a need, but will probably get around to it soon
I see. So as far as we know there's currently no way to write to file in Mojo yet?
You can call the CAPIs
i.e write your own fwrite wrapper in the same way I did an fread wrapper
Cool, I can try that out
Thanks!
Here we go" https://github.com/ShuzhaoFeng/mojo-minwa
GitHub
GitHub - ShuzhaoFeng/mojo-minwa: The minimal library you need to wr...
The minimal library you need to write / append file in Mojo - GitHub - ShuzhaoFeng/mojo-minwa: The minimal library you need to write / append file in Mojo
Nice 🙂
@Tenesis thought I'd ping you that I've since added a buffered writer
Awesome. 🥳 Thanks Lukas
By the way there’s now the
open
method available, but I’m pretty sure it’s not buffered yet, so its use will depend on what you’re doingIt is simple with the version 0.4.0 , you have to see the documention of this version 🙏:mojo: :python:
Thanks @Elaid Tebabkha! 🩵
Will check it out now
Congrats @bhavnicksm, you just advanced to level 1!
@Elaid Tebabkha @lukas I was trying out the open method yesterday and I am facing issues with both reading and writing to a file. Mojo v0.4 doesn't seem to be able to parse it properly. Here's a screenshot of what I faced, and the code I was trying to execute
It's a working example .. you may add raises to your main function ?
@Balderdash Oh with raises it seems to work! Thanks
Do you know why this works though? I don’t understand this properly
When you call a function, which throws an exception you need either to catch and handle it or define in your function by using key 'raises' its given to its caller to handle it.
Or use try except finally.🙏
Yes, try-except also seems to work
You can also write The code in python an import it inside the Mojo code like a PythonObject and execute the mojo code .