mojo
mojo copied to clipboard
[Feature Request] Open files like python
Request
if there is already a way to do this please let me know
Please add a mojo internal way to open files, using python interop I wasn't able to get the files contents I tried many things but nothing seems to work
Motivation
I would like to work with data that I upload
Description and Requirements
open() / readFile() should give bytes / string data from files
You can do this.
from PythonInterface import Python
builtins = Python.import_module("builtins")
f = builtins.open("text.txt")
builtins.print(f.read())
f.close()
You can do this.
from PythonInterface import Python builtins = Python.import_module("builtins") f = builtins.open("text.txt") builtins.print(f.read()) f.close()
Is there any way to get it as a mojo StringRef ?
@JanzenJohn No well defined interface yet. But this seems working for now
from PythonInterface import Python
builtins = Python.import_module("builtins")
f = builtins.open("text.txt")
s = f.read()
f.close()
let p = Python()
let sref: StringRef = p.__str__(s)
print(sref)
We need to build out a ton of API surface area, and this absolutely makes sense. That said, we're missing some language features necessary before really building out the APIs - these will come in in the next few months. @abduld how do you prefer to organize these requests for stdlib features?
Using this
def read_file(path: String):
let py = Python.import_module("builtins")
let file = py.open(path)
let text = file.read()
file.close()
# not yet supported...
# let mojo_text = String(text)
let python = Python()
let mojo_text: StringRef = python.__str__(text)
return mojo_text
I get
error: invalid mutation of immutable value 'python.impl'
let mojo_text: StringRef = python.__str__(text)
Am I doing something wrong?
As the error message suggests, it works with var python = Python()
...
In Mojo 0.4 we introduced a file module (see https://docs.modular.com/mojo/stdlib/builtin/file.html )
That is now the preferred way to read / write files instead of using through the Python route