📁 Go File Handling – Read, Write, Delete, Rename, and More
🧲 Introduction – Why Learn File Handling in Go?
File I/O is fundamental to any programming language. In Go, file handling is powered by the os, io, bufio, and encoding/csv packages, giving you clean and efficient ways to read, write, modify, and manage files on the system.
🎯 In this guide, you’ll learn:
- How to read files by word, line, and CSV rows
- How to write or append to files without truncating
- How to delete, rename, and truncate files
- How to handle file errors safely
📘 Topics Covered
| 🔹 Topic | 📖 Description |
|---|---|
| 📖 Read File by Word | Use buffered readers and Scanner.Split() for word-wise reading |
| 📖 Read File by Line | Use bufio.Scanner to process line-by-line |
| 📄 Read CSV Files | Use encoding/csv to parse comma-separated values |
| 🗑️ Delete File | Use os.Remove() to delete files |
| 🔁 Rename & Move File | Use os.Rename() to rename or relocate files |
| ✂️ Truncate File | Use os.Truncate() to reduce file size |
| 📝 Read/Write without Truncation | Open with flags to append or modify without destroying data |
📖 Go – Read File by Word
file, _ := os.Open("data.txt")
defer file.Close()
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanWords)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
✅ ScanWords splits input into individual words.
Use scanner.Err() to handle read errors.
📖 Go – Read File by Line
file, _ := os.Open("data.txt")
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
✅ Line-by-line reading is memory-efficient for large files.
📄 Go – Read CSV Files
file, _ := os.Open("records.csv")
defer file.Close()
reader := csv.NewReader(file)
records, _ := reader.ReadAll()
for _, row := range records {
fmt.Println("Name:", row[0], "Age:", row[1])
}
✅ Supports custom delimiters using reader.Comma = ';'.
🗑️ Go – Delete File
err := os.Remove("old.txt")
if err != nil {
fmt.Println("Error deleting file:", err)
}
✅ Deletes file from filesystem.
Use os.RemoveAll() to delete directories.
🔁 Go – Rename & Move File
err := os.Rename("old.txt", "archive/new.txt")
if err != nil {
fmt.Println("Rename failed:", err)
}
✅ Use absolute/relative paths to rename or move.
✂️ Go – Truncate File
err := os.Truncate("log.txt", 100)
if err != nil {
fmt.Println("Truncate error:", err)
}
✅ Cuts file to 100 bytes.
Use to shrink log files or limit disk usage.
📝 Go – Read/Write without Truncation
file, err := os.OpenFile("data.txt", os.O_RDWR|os.O_APPEND, 0644)
defer file.Close()
file.WriteString("Appended line\n")
| Flag | Description |
|---|---|
os.O_APPEND | Write without erasing |
os.O_CREATE | Create file if not exists |
os.O_RDWR | Read & write |
os.O_TRUNC | Truncate file to zero |
📌 Summary – Recap & Next Steps
Go’s file handling toolkit is concise, fast, and safe. Whether you’re building a log system, data processor, or file-based utility, these operations give you full control over I/O without complexity.
🔍 Key Takeaways:
- Use
bufio.Scannerto read files by word or line - Parse CSV using
encoding/csv - Delete, move, rename files using
osfunctions - Truncate files safely with
os.Truncate() - Open files with mode flags to avoid data loss
⚙️ Real-World Applications:
- Log file rotation and truncation
- Import/export CSV data
- Append-only transaction logs
- File-based configuration and backups
❓ Frequently Asked Questions
❓ How do I check if a file exists in Go?
✅ Use:
if _, err := os.Stat("file.txt"); err == nil {
fmt.Println("Exists")
}
❓ Can I append data without overwriting the file?
✅ Yes. Use os.O_APPEND:
os.OpenFile("file.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
❓ What happens if I truncate a file that doesn’t exist?
✅ os.Truncate() will return an error unless the file already exists.
❓ Can I read and write the same file simultaneously?
✅ Yes, with os.O_RDWR, but use caution with file position and concurrency.
❓ How do I move a file in Go?
✅ Just use os.Rename() with a different path.
Share Now :
