mojo icon indicating copy to clipboard operation
mojo copied to clipboard

[Feature Request] Open files like python

Open JanzenJohn opened this issue 1 year ago • 4 comments

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

JanzenJohn avatar May 13 '23 15:05 JanzenJohn

You can do this.

from PythonInterface import Python

builtins = Python.import_module("builtins")
f = builtins.open("text.txt")
builtins.print(f.read())
f.close()

czheo avatar May 13 '23 16:05 czheo

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 avatar May 13 '23 17:05 JanzenJohn

@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)

czheo avatar May 13 '23 17:05 czheo

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?

lattner avatar May 14 '23 09:05 lattner

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()...

paugier avatar Nov 07 '23 15:11 paugier

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

abduld avatar Nov 07 '23 15:11 abduld