Creating files from code

Is there a way to create a file from code? I've tried using a python script:
def create_proj(path: str):
with open(path + "/main.mojo", "x") as f:
f.write("text goes here")
def create_proj(path: str):
with open(path + "/main.mojo", "x") as f:
f.write("text goes here")
then:
from python import *

fn create_proj(folder: String) raises:
Python.add_to_path(".")
var file = Python.import_module("createproj")
file.create_proj(folder)
from python import *

fn create_proj(folder: String) raises:
Python.add_to_path(".")
var file = Python.import_module("createproj")
file.create_proj(folder)
but I have been getting this error:
Unhandled exception caught during execution: module 'createproj' has no attribute 'create_proj'
/home/[USERNAME]/pyregl/.magic/envs/default/bin/mojo: error: execution exited with a non-zero result: 1
Unhandled exception caught during execution: module 'createproj' has no attribute 'create_proj'
/home/[USERNAME]/pyregl/.magic/envs/default/bin/mojo: error: execution exited with a non-zero result: 1
4 Replies
Lil'Nish
Lil'Nish4w ago
You can use the open() function in a context manager in Mojo the same way you would in python, there's no need to interop any python code for this.
fn create_proj(filepath: String) raises:
if os.path.exists(filepath):
raise Error("File already exists.")

with open(filepath, "w") as f:
f.write(String("text goes here"))
fn create_proj(filepath: String) raises:
if os.path.exists(filepath):
raise Error("File already exists.")

with open(filepath, "w") as f:
f.write(String("text goes here"))
However, I don't think Mojo supports opening a file in "x" mode yet, so you'll need to ensure that the file doesn't already exist manually
banananas
banananasOP4w ago
That's the problem, I want to literally create a file
Lil'Nish
Lil'Nish4w ago
"w" mode also creates the file The only difference from "x" mode is that it will overwrite an existing file with the same name (if it's there) instead of throwing an exception
banananas
banananasOP4w ago
Huh, really? I'm going to have to try that when I get home Yep, that works well honestly i'm surprised i didn't think of this earlier
Want results from more Discord servers?
Add your server