File I/O in Mojo: How to Open, Read, Write, and Handle CSV Files

Mojo

Introduction

File input and output (I/O) are essential in almost any programming task. Whether you’re logging data, reading configurations, or processing files, understanding how to open, read, and write files is fundamental. In this article, we’ll explore how to perform file I/O in Mojo, including reading and writing text files and working with CSV data.

1. Opening and Writing to a File

Mojo allows you to open a file using the open function, similar to Python. To write text to a file, use the mode "w" (write).

let file = open("example.txt", "w")
file.write("Hello from Mojo!\n")
file.close()

This code creates (or overwrites) a file named example.txt and writes a single line to it.

2. Reading from a File

To read a file, open it in "r" (read) mode. You can read the entire content or loop through each line.

let file = open("example.txt", "r")
let content = file.read()
print(content)
file.close()

You can also iterate through the file line by line:

let file = open("example.txt", "r")
for line in file:
    print("Line:", line.strip())
file.close()

3. Writing CSV Data

Writing structured data like CSV is straightforward. Use commas to separate values and write each line accordingly.

let file = open("data.csv", "w")
file.write("name,age,city\n")
file.write("Alice,30,New York\n")
file.write("Bob,25,London\n")
file.close()

4. Reading and Parsing CSV Files

While Mojo doesn’t have a built-in CSV parser (yet), you can manually split each line by commas to simulate it.

let file = open("data.csv", "r")
for line in file:
    let fields = line.strip().split(",")
    print("Name:", fields[0], "Age:", fields[1], "City:", fields[2])
file.close()

This method works well for simple CSV files without quoted fields or special characters.

5. Notes on File Handling

  • Always use close() to free system resources.
  • Mojo may introduce context managers (like Python’s with) in the future.
  • Handle exceptions to avoid crashes from missing files.

Conclusion

Working with files in Mojo is clean and Python-like, making it accessible for beginners. With basic open, read, and write operations, you can build simple logging systems, data importers, or CSV processors. As the Mojo language evolves, expect to see even more advanced file handling features added.

Comment

Copied title and URL