Learn Julia Β· 9/15

File I/O & Working with Data

8 min read

πŸ“ File I/O & Working with Data in Julia

Welcome, data wrangler! 🀠 You've wrangled variables and tamed loops. Now it's time to face the real world... of data! Most of the time, the data we need isn't neatly typed into our code. It lives in files, sometimes small, sometimes monstrously large. In this chapter, we'll learn how to communicate with these files, read their secrets, and write our own.

Think of your Julia program as a well-organized office. Until now, all the information has been in your head (the computer's memory). But what happens when you go home for the day (shut down the program)? All that information vanishes. File I/O (Input/Output) is like having a filing cabinet. You can store your work and pick it up later. You can also receive reports (files) from other departments to work on.


πŸ“ Reading and Writing Text Files

The Problem: You have a brilliant idea for a program that analyzes your favorite quotes. You could type them all into a giant string inside your code, but that would be messy and hard to update. What you need is a way to read these quotes from a simple text file.

The Solution: Julia provides simple yet powerful functions to read from and write to text files.

Let's start with a file named quotes.txt with the following content:

smalltalk
"The best way to predict the future is to invent it." - Alan Kay
"Simplicity is the ultimate sophistication." - Leonardo da Vinci
"Walking on water and developing software from a specification are easy if both are frozen." - Edward V. Berard

Reading Files πŸ“–

The most common way to read a file in Julia is line by line. This is super efficient because you don't have to load the entire file into memory at once. Imagine trying to read a 10 GB log file – your computer would not be happy.

The eachline function is your best friend here. It lets you loop through the lines of a file without loading it all at once.

julia
# Open the file for reading
f = open("quotes.txt", "r")

# Loop through each line
for line in eachline(f)
    println("Here's a quote: ", line)
end

# Always remember to close the file!
close(f)

What's happening under the hood? When you open a file, Julia gets a "file handle" from the operating system. This is like a bookmark that tells the OS where you are in the file. eachline then reads just enough data to get the next line, and close tells the OS you're done, releasing the bookmark.

An even better way: The do block

What if your program has an error while the file is open? The close(f) line might never be reached. This is like leaving a library book open on a table and walking away. It's not a disaster, but it's not good practice.

Julia provides a more robust way to handle this with a do block. This ensures the file is closed no matter what.

julia
open("quotes.txt", "r") do f
    for line in eachline(f)
        println("A wise person said: ", line)
    end
end
# No need to call close(f), it's done automatically!

You can also read the entire file into a single string with read, but be cautious with large files!

julia
# Be careful with large files!
all_quotes = read("quotes.txt", String)
println(all_quotes)

Writing Files ✍️

Now, let's say your program generates a new, profound quote and you want to save it for posterity.

You can open a file in "write" mode ("w") to create a new file or overwrite an existing one.

julia
open("new_quote.txt", "w") do f
    write(f, "The early bird gets the worm, but the second mouse gets the cheese.")
end

If you run this code, you'll find a new file new_quote.txt in the same directory.

What if you want to add to an existing file? Use "append" mode ("a").

julia
open("new_quote.txt", "a") do f
    write(f, "\nAnother brilliant thought!") # \n adds a new line
end

πŸ“Š Working with CSV and Delimited Files (CSV.jl)

The Problem: Simple text files are great, but most real-world data is structured. Think of spreadsheets with rows and columns. One of the most common formats for this is the Comma-Separated Values (CSV) file. How do we read this structured data into Julia without manually splitting every line by commas?

The Solution: The CSV.jl package is the industry standard for working with CSV files in Julia. It's fast, flexible, and can handle a huge variety of delimited file formats.

First, you need to add the package. In the Julia REPL, press ] to enter the package manager, then:

routeros
pkg> add CSV

Let's imagine we have a file named grades.csv:

csv
student_id,name,grade
1,Alice,88
2,Bob,92
3,Charlie,75

Reading a CSV File 🧐

With CSV.jl, reading this file is a one-liner:

julia
using CSV
using DataFrames # We'll talk more about this next!

# Read the CSV file into a DataFrame
df = CSV.read("grades.csv", DataFrame)

println(df)

What's a DataFrame? We're getting ahead of ourselves, but for now, think of it as an in-memory representation of a spreadsheet table. CSV.read is smart enough to figure out the column names from the first line (the header) and the data types of each column.

Writing a CSV File πŸ“

Let's say we want to add a new student and save the result. We'll dive into modifying DataFrames in the next section, but for now, let's just create a new one from scratch and write it to a file.

julia
using CSV
using DataFrames

# Create a new DataFrame
new_grades = DataFrame(student_id = [4, 5], name = ["David", "Eve"], grade = [95, 89])

# Write the DataFrame to a new CSV file
CSV.write("new_grades.csv", new_grades)

This will create a new_grades.csv file with the new data, complete with a header row. CSV.jl takes care of all the formatting for you.


ሠ Introduction to DataFrames.jl

The Problem: We've read our CSV data. Now what? It's sitting in a DataFrame, but what exactly is that, and how do we work with it? We need a way to easily access columns, rows, and individual cells.

The Solution: DataFrames.jl is one of the cornerstone packages in the Julia data science ecosystem. It provides the DataFrame type, a powerful and intuitive object for working with tabular data.

Think of a DataFrame as a super-powered spreadsheet inside Julia. It has rows and columns, and each column has a name and a specific data type (e.g., integers, strings, dates).

First, ensure you have the package:

routeros
pkg> add DataFrames

Creating a DataFrame

We already saw how to create a DataFrame by reading a CSV. You can also create one from scratch:

julia
using DataFrames

df = DataFrame(
    Name = ["Frodo", "Sam", "Merry", "Pippin"],
    Race = ["Hobbit", "Hobbit", "Hobbit", "Hobbit"],
    Age = [50, 33, 36, 28]
)

println(df)

This gives you a nice, clean table to work with.

Basic Inspection

Once you have a DataFrame, the first thing you'll want to do is get a feel for what's inside.

julia
# Get the size (rows, columns)
println(size(df))

# Get the column names
println(names(df))

# Get the first few rows
println(first(df, 2))

# Get a summary of the data types and some stats
println(describe(df))

Accessing Data

You can access columns in a few ways, most commonly using a Symbol (a colon followed by the name) or a string.

julia
# Access the 'Name' column
println(df.Name)
println(df[!, :Name]) # The ! means all rows

# Access a specific row (e.g., the 3rd row)
println(df[3, :]) # The : means all columns

# Access a specific cell (3rd row, 'Age' column)
println(df[3, :Age])

πŸ”§ Basic Data Manipulation: Filtering, Grouping, and Sorting

The Problem: Your DataFrame is loaded, but you only want to see a subset of the data. Maybe you only want to see the Hobbits who are older than 35, or you want to find the average age by race. How do you perform these common data manipulation tasks?

The Solution: DataFrames.jl provides a rich set of functions for slicing and dicing your data.

Let's use a slightly more complex DataFrame for these examples:

julia
using DataFrames

df = DataFrame(
    Name = ["Frodo", "Sam", "Aragorn", "Legolas", "Gimli"],
    Race = ["Hobbit", "Hobbit", "Human", "Elf", "Dwarf"],
    Age = [50, 33, 87, 2931, 139]
)

Filtering Rows

To select rows based on a condition, you can use boolean indexing.

julia
# Find all the Hobbits
hobbits_df = df[df.Race .== "Hobbit", :]
println(hobbits_df)

# Find characters older than 100
old_characters_df = df[df.Age .> 100, :]
println(old_characters_df)

A fun fact: The . before == and > is crucial. It tells Julia to apply the comparison element by element to the entire Race or Age column.

Sorting Data

Sorting is straightforward with the sort function.

julia
# Sort by age in ascending order
sorted_by_age = sort(df, :Age)
println(sorted_by_age)

# Sort by age in descending order
sorted_by_age_desc = sort(df, :Age, rev=true)
println(sorted_by_age_desc)

Grouping and Aggregating

This is where the real power comes in. Let's say we want to find the average age for each race. The "split-apply-combine" strategy is perfect for this:

  1. Split the DataFrame into groups based on Race.
  2. Apply the mean function to the Age column of each group.
  3. Combine the results into a new DataFrame.

The groupby and combine functions work together to achieve this.

julia
using Statistics # for the mean function

# Group by 'Race' and calculate the mean age for each
average_age_by_race = combine(groupby(df, :Race), :Age => mean)
println(average_age_by_race)

This is a very common pattern in data analysis. You can perform all sorts of aggregations, like sum, minimum, maximum, etc.

This is just the beginning of your journey with data in Julia. These tools will allow you to handle a vast array of data-related tasks, from simple file manipulation to complex data analysis.


πŸ“š Further Reading

Challenge

Challenge: Sales Data Analysis Pipeline

You are given a string containing product sales data in CSV format. Your task is to implement a data analysis pipeline using DataFrames.jl and CSV.jl to process this data and produce a summary report.

Your tasks are to:

  1. Parse the multi-line string sales_data_csv into a DataFrame named sales_df.
  2. Create a new DataFrame by filtering sales_df to include only rows where the Quantity is greater than 1 and the Status is exactly "Completed".
  3. To this filtered DataFrame, add a new column named Revenue. The value for each row in this column should be the product of its UnitPrice and Quantity.
  4. Group the resulting DataFrame by the Category column.
  5. Generate a summary report by calculating two aggregates for each category:
    • The sum of Revenue, naming the resulting column TotalRevenue.
    • The mean of UnitPrice, naming the resulting column AvgPrice.
  6. Store this aggregated data in a new DataFrame called summary_df.
  7. Sort summary_df by the TotalRevenue column in descending order.
  8. Finally, convert the sorted summary_df back into a CSV-formatted string and print the result to standard output.

Expected result

Your script should print a single string formatted as a CSV. The string must have a header row and three data rows, sorted by TotalRevenue in descending order. The content of the string, including newlines, should be exactly:

csv
Category,TotalRevenue,AvgPrice
Electronics,900.0,450.0
Clothing,357.48,67.245
Books,173.45,22.245
julia

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.