How do I open files to read/write in Mojo?

I want to do the equivalent of the following Python code:
with open(file.txt, 'r') as file:
x = file.read()
with open(file.txt, 'r') as file:
x = file.read()
How can I do this?
23 Replies
sa-code
sa-code12mo ago
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.
bhavnicksm
bhavnicksm12mo ago
@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
lukas
lukas12mo ago
The read code has an example at the top of the file
bhavnicksm
bhavnicksm12mo ago
Thanks, will try it out!
Tenesis
Tenesis12mo ago
@lukas can you give an example on how to write files as well? Thanks a lot!
lukas
lukas12mo ago
I haven’t written a wrapper for that yet I haven’t had a need, but will probably get around to it soon
Tenesis
Tenesis12mo ago
I see. So as far as we know there's currently no way to write to file in Mojo yet?
lukas
lukas12mo ago
You can call the CAPIs i.e write your own fwrite wrapper in the same way I did an fread wrapper
Tenesis
Tenesis12mo ago
Cool, I can try that out Thanks!
Tenesis
Tenesis12mo ago
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
lukas
lukas12mo ago
Nice 🙂 @Tenesis thought I'd ping you that I've since added a buffered writer
Tenesis
Tenesis12mo ago
Awesome. 🥳 Thanks Lukas
lukas
lukas12mo ago
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 doing
Elaid Tebabkha
Elaid Tebabkha12mo ago
It is simple with the version 0.4.0 , you have to see the documention of this version 🙏:mojo: :python:
bhavnicksm
bhavnicksm12mo ago
Thanks @Elaid Tebabkha! 🩵 Will check it out now
Want results from more Discord servers?
Add your server