Go (Golang) / File Handling and I/O Operations
Reading and Writing Files in Go
In this tutorial, we will explore how to handle files in Go. We will learn how to open, read, write, and close files using the 'os' package.
Section overview
5 resourcesExplains how to read and write files, work with directories, and handle I/O operations in Go.
Reading and Writing Files in Go
1. Introduction
In this tutorial, we will dive into how to handle files in Go programming language. Specifically, we will be using the os package in Go to open, read, write, and close files.
By the end of this tutorial, you will learn:
- How to open a file in Go
- How to read from a file
- How to write to a file
- How to close a file once done
Prerequisites: Basic understanding of Go programming language.
2. Step-by-Step Guide
Go has built-in support for reading and writing files using the os package. Here are the key concepts:
Opening a File: The os.Open() function is used to open a file.
file, err := os.Open("test.txt")
Reading a File: The io/ioutil package provides helper functions for reading a file.
data, err := ioutil.ReadFile("test.txt")
Writing to a File: The os.Create() function is used to create a file, and file.WriteString() is used to write to a file.
file, err := os.Create("test.txt")
n, err := file.WriteString("Hello World")
Closing a File: The file.Close() function is used to close the file.
err = file.Close()
3. Code Examples
Let's look at some practical examples:
Example 1: Reading a file
package main
import (
"fmt"
"io/ioutil"
"log"
)
func main() {
// Open file for reading
data, err := ioutil.ReadFile("test.txt")
if err != nil {
log.Fatalf("Failed reading data from file: %s", err)
}
fmt.Printf("Data read: %s\n", data)
}
In this example, we open a file called "test.txt" and read all data from it.
Example 2: Writing a file
package main
import (
"log"
"os"
)
func main() {
// Create a new file
file, err := os.Create("test.txt")
if err != nil {
log.Fatalf("Failed creating file: %s", err)
}
// Write some text line-by-line to file.
_, err = file.WriteString("Hello\nWorld")
if err != nil {
log.Fatalf("Failed writing to file: %s", err)
}
// Close the file
file.Close()
}
In this example, we create a new file and write two lines of text to it. Don't forget to close the file after writing to it.
4. Summary
In this tutorial, we learned how to open, read, write, and close files in Go using the os and io/ioutil packages.
For further learning, explore how to handle errors in Go and how to read and write to CSV and JSON files.
Check out the official Go documentation for more details.
5. Practice Exercises
- Write a program that reads a file and counts the number of lines.
- Write a program that writes the numbers from 1 to 10 into a file, each on a new line.
- Write a program that reads a file and prints only the even numbered lines.
Solutions
1.
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func main() {
file, err := os.Open("test.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
lineCount := 0
for scanner.Scan() {
lineCount++
}
fmt.Println("Number of lines:", lineCount)
}
This program opens the file, scans each line, and increments a counter for each line.
2.
package main
import (
"fmt"
"log"
"os"
)
func main() {
file, err := os.Create("numbers.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
for i := 1; i <= 10; i++ {
fmt.Fprintln(file, i)
}
}
This program creates a file and writes the numbers 1 to 10, each on a new line.
3.
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func main() {
file, err := os.Open("test.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
lineNumber := 0
for scanner.Scan() {
lineNumber++
if lineNumber%2 == 0 {
fmt.Println(scanner.Text())
}
}
}
This program reads a file and prints only the even numbered lines.
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article