Go Tutorial
Estimated reading: 4 minutes 53 views

📁 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 WordUse buffered readers and Scanner.Split() for word-wise reading
📖 Read File by LineUse bufio.Scanner to process line-by-line
📄 Read CSV FilesUse encoding/csv to parse comma-separated values
🗑️ Delete FileUse os.Remove() to delete files
🔁 Rename & Move FileUse os.Rename() to rename or relocate files
✂️ Truncate FileUse os.Truncate() to reduce file size
📝 Read/Write without TruncationOpen 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")
FlagDescription
os.O_APPENDWrite without erasing
os.O_CREATECreate file if not exists
os.O_RDWRRead & write
os.O_TRUNCTruncate 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.Scanner to read files by word or line
  • Parse CSV using encoding/csv
  • Delete, move, rename files using os functions
  • 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Go – File Handling

Or Copy Link

CONTENTS
Scroll to Top