Reading & Writing Files in Go

List Topics
February 18, 2025
No Comments
6 min read

In Go, file handling is done using the os and io/ioutil packages. These packages provide functions for reading from and writing to files, which allows Go programs to interact with the file system. The basic operations include opening, reading, writing, and closing files.

1️⃣ Reading Files in Go

To read from a file in Go, you can use the os.Open function to open the file, and then read its contents using various methods like Read, ReadFile, or Scanner.

🔹 Example: Reading a file using os.Open and Read:

Go
package main

import (
    "fmt"
    "os"
)

func main() {
    // Open the file for reading
    file, err := os.Open("example.txt")
    if err != nil {
        fmt.Println("Error opening file:", err)
        return
    }
    defer file.Close()

    // Read the file's contents
    buffer := make([]byte, 1024)  // Create a buffer to store the file's data
    n, err := file.Read(buffer)
    if err != nil {
        fmt.Println("Error reading file:", err)
        return
    }

    // Print the contents of the file
    fmt.Println("File contents:", string(buffer[:n]))
}

🔹 Output (if example.txt contains "Hello, Go World!"):

Bash
File contents: Hello, Go World!

👉 In this example:

  • os.Open is used to open the file.
  • file.Read reads the contents of the file into the buffer.
  • The defer file.Close() ensures that the file is closed after the function finishes.

2️⃣ Writing Files in Go

To write data to a file, you can use os.Create to create or overwrite the file and then use methods like Write or WriteString to write content to it.

🔹 Example: Writing to a file using os.Create and Write:

Go
package main

import (
    "fmt"
    "os"
)

func main() {
    // Create or overwrite the file for writing
    file, err := os.Create("example.txt")
    if err != nil {
        fmt.Println("Error creating file:", err)
        return
    }
    defer file.Close()

    // Write to the file
    _, err = file.WriteString("Hello, Go World!")
    if err != nil {
        fmt.Println("Error writing to file:", err)
        return
    }

    fmt.Println("Data written to file successfully")
}

🔹 Output:

Bash
Data written to file successfully

👉 In this example:

  • os.Create creates or opens a file for writing, overwriting the file if it already exists.
  • file.WriteString writes the string "Hello, Go World!" to the file.

3️⃣ Using ioutil for Simplified File Reading and Writing

The ioutil package provides simpler functions like ioutil.ReadFile and ioutil.WriteFile for reading and writing files with a single line of code.

🔹 Example: Reading a file using ioutil.ReadFile:

Go
package main

import (
    "fmt"
    "io/ioutil"
)

func main() {
    // Read the file using ioutil.ReadFile
    content, err := ioutil.ReadFile("example.txt")
    if err != nil {
        fmt.Println("Error reading file:", err)
        return
    }

    // Print the file contents
    fmt.Println("File contents:", string(content))
}

🔹 Example: Writing to a file using ioutil.WriteFile:

Go
package main

import (
    "fmt"
    "io/ioutil"
)

func main() {
    // Write to the file using ioutil.WriteFile
    err := ioutil.WriteFile("example.txt", []byte("Hello, Go World!"), 0644)
    if err != nil {
        fmt.Println("Error writing to file:", err)
        return
    }

    fmt.Println("Data written to file successfully")
}

🔹 Output for Writing Example:

Bash
Data written to file successfully

👉 The ioutil functions simplify file operations:

  • ioutil.ReadFile reads the entire content of the file into memory and returns it as a byte slice.
  • ioutil.WriteFile writes data to the file, and you can specify the file permissions (e.g., 0644).

4️⃣ Append Data to a File

If you want to append data to a file without overwriting it, you can open the file in append mode using os.OpenFile.

🔹 Example: Appending data to a file:

Go
package main

import (
    "fmt"
    "os"
)

func main() {
    // Open the file in append mode
    file, err := os.OpenFile("example.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
    if err != nil {
        fmt.Println("Error opening file:", err)
        return
    }
    defer file.Close()

    // Append data to the file
    _, err = file.WriteString("\nAppended content!")
    if err != nil {
        fmt.Println("Error appending to file:", err)
        return
    }

    fmt.Println("Data appended to file successfully")
}

🔹 Output:

Bash
Data appended to file successfully

👉 In this example, os.OpenFile is used with flags os.O_APPEND to open the file in append mode. The new content is then added at the end of the file.

Summary:

  • Reading files: Use os.Open and Read or the simpler ioutil.ReadFile to read the contents of a file.
  • Writing files: Use os.Create and WriteString or the simpler ioutil.WriteFile to write content to a file.
  • Appending data: Use os.OpenFile with the os.O_APPEND flag to append data to a file without overwriting it.
  • Always ensure to close the file after use using defer file.Close().

These methods provide efficient and simple ways to handle files in Go, giving you control over reading, writing, and appending file content.


Go তে ফাইল হ্যান্ডলিং: ফাইল পড়া ও লেখা

Go-তে ফাইল হ্যান্ডলিং os এবং io/ioutil প্যাকেজগুলির মাধ্যমে করা হয়। এই প্যাকেজগুলি ফাইলের সাথে ইন্টারঅ্যাক্ট করার জন্য ফাইল পড়া, লেখা, খুলা এবং বন্ধ করার মত কার্যাবলী প্রদান করে। মূলত, ফাইলের সাথে কাজ করার জন্য কিছু সাধারণ অপারেশন রয়েছে।

1️⃣ ফাইল পড়া (Reading Files) Go তে

Go তে ফাইল পড়ার জন্য os.Open ফাংশন ব্যবহার করা হয়, তারপর বিভিন্ন পদ্ধতি যেমন Read, ReadFile, বা Scanner দিয়ে তার কনটেন্ট পড়া যায়।

🔹 উদাহরণ: os.Open এবং Read ব্যবহার করে ফাইল পড়া:

Go
package main

import (
    "fmt"
    "os"
)

func main() {
    // ফাইলটি খুলুন পড়ার জন্য
    file, err := os.Open("example.txt")
    if err != nil {
        fmt.Println("ফাইল খুলতে সমস্যা:", err)
        return
    }
    defer file.Close()

    // ফাইলের কনটেন্ট পড়ুন
    buffer := make([]byte, 1024)  // ফাইলের ডাটা সংরক্ষণের জন্য একটি বাফার তৈরি করুন
    n, err := file.Read(buffer)
    if err != nil {
        fmt.Println("ফাইল পড়তে সমস্যা:", err)
        return
    }

    // ফাইলের কনটেন্ট প্রিন্ট করুন
    fmt.Println("ফাইলের কনটেন্ট:", string(buffer[:n]))
}

🔹 আউটপুট (যদি example.txt তে "Hello, Go World!" লেখা থাকে):

Bash
ফাইলের কনটেন্ট: Hello, Go World!

👉 এই উদাহরণে:

  • os.Open ব্যবহার করে ফাইলটি খোলা হয়।
  • file.Read ফাংশন দিয়ে ফাইলের কনটেন্ট বাফারে পড়া হয়।
  • defer file.Close() ফাংশনটি নিশ্চিত করে যে ফাইলটি ফাংশনের শেষে বন্ধ হয়ে যাবে।

2️⃣ ফাইল লেখা (Writing Files) Go তে

ফাইলের মধ্যে ডাটা লেখার জন্য os.Create ব্যবহার করা হয় যাতে ফাইল তৈরি হয় বা যদি ফাইল ইতিমধ্যেই থাকে, তা ওভাররাইট করা হয়। তারপর Write বা WriteString পদ্ধতি দিয়ে ডাটা লেখা যায়।

🔹 উদাহরণ: os.Create এবং Write ব্যবহার করে ফাইল লেখা:

Go
package main

import (
    "fmt"
    "os"
)

func main() {
    // ফাইল তৈরি করুন অথবা লেখার জন্য খুলুন
    file, err := os.Create("example.txt")
    if err != nil {
        fmt.Println("ফাইল তৈরি করতে সমস্যা:", err)
        return
    }
    defer file.Close()

    // ফাইলে লেখা
    _, err = file.WriteString("Hello, Go World!")
    if err != nil {
        fmt.Println("ফাইলে লেখা করতে সমস্যা:", err)
        return
    }

    fmt.Println("ফাইলে ডাটা সফলভাবে লেখা হয়েছে")
}

🔹 আউটপুট:

Bash
ফাইলে ডাটা সফলভাবে লেখা হয়েছে

👉 এই উদাহরণে:

  • os.Create ফাইলটি তৈরি বা খুলে লেখার জন্য প্রস্তুত করে।
  • file.WriteString ফাংশন দিয়ে "Hello, Go World!" স্ট্রিংটি ফাইলে লেখা হয়।

3️⃣ ioutil ব্যবহার করে সহজ ফাইল পড়া ও লেখা

ioutil প্যাকেজটি সহজ ফাংশন যেমন ioutil.ReadFile এবং ioutil.WriteFile প্রদান করে যা এক লাইনে ফাইল পড়া এবং লেখা সম্ভব করে তোলে।

🔹 উদাহরণ: ioutil.ReadFile ব্যবহার করে ফাইল পড়া:

Go
package main

import (
    "fmt"
    "io/ioutil"
)

func main() {
    // ioutil.ReadFile ব্যবহার করে ফাইল পড়া
    content, err := ioutil.ReadFile("example.txt")
    if err != nil {
        fmt.Println("ফাইল পড়তে সমস্যা:", err)
        return
    }

    // ফাইলের কনটেন্ট প্রিন্ট করুন
    fmt.Println("ফাইলের কনটেন্ট:", string(content))
}

🔹 উদাহরণ: ioutil.WriteFile ব্যবহার করে ফাইল লেখা:

Go
package main

import (
    "fmt"
    "io/ioutil"
)

func main() {
    // ioutil.WriteFile ব্যবহার করে ফাইল লেখা
    err := ioutil.WriteFile("example.txt", []byte("Hello, Go World!"), 0644)
    if err != nil {
        fmt.Println("ফাইলে লেখা করতে সমস্যা:", err)
        return
    }

    fmt.Println("ফাইলে ডাটা সফলভাবে লেখা হয়েছে")
}

🔹 আউটপুট লেখার উদাহরণ:

Bash
ফাইলে ডাটা সফলভাবে লেখা হয়েছে

👉 ioutil ফাংশনগুলি ফাইল অপারেশনগুলোকে সহজ করে তোলে:

  • ioutil.ReadFile পুরো ফাইলের কনটেন্ট একটি বাইট স্লাইস হিসেবে ফিরিয়ে দেয়।
  • ioutil.WriteFile ফাইলের মধ্যে ডাটা লেখে এবং আপনি ফাইল পারমিশন (যেমন, 0644) নির্ধারণ করতে পারেন।

4️⃣ ফাইলে ডাটা অ্যাপেন্ড করা

যদি আপনি ফাইলে নতুন ডাটা অ্যাপেন্ড করতে চান (ওভাররাইট না করে), তাহলে os.OpenFile ব্যবহার করে ফাইলটি অ্যাপেন্ড মোডে খুলতে পারেন।

🔹 উদাহরণ: ফাইলে ডাটা অ্যাপেন্ড করা:

Go
package main

import (
    "fmt"
    "os"
)

func main() {
    // ফাইলটি অ্যাপেন্ড মোডে খুলুন
    file, err := os.OpenFile("example.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
    if err != nil {
        fmt.Println("ফাইল খুলতে সমস্যা:", err)
        return
    }
    defer file.Close()

    // ফাইলে ডাটা অ্যাপেন্ড করুন
    _, err = file.WriteString("\nAppended content!")
    if err != nil {
        fmt.Println("ফাইলে অ্যাপেন্ড করতে সমস্যা:", err)
        return
    }

    fmt.Println("ফাইলে ডাটা সফলভাবে অ্যাপেন্ড হয়েছে")
}

🔹 আউটপুট:

Bash
ফাইলে ডাটা সফলভাবে অ্যাপেন্ড হয়েছে

👉 এই উদাহরণে, os.OpenFile ফাংশনটি os.O_APPEND ফ্ল্যাগ ব্যবহার করে ফাইলটি অ্যাপেন্ড মোডে খোলে। নতুন কনটেন্ট ফাইলের শেষে যোগ করা হয়।

সারাংশ:

  • ফাইল পড়া: os.Open এবং Read বা সহজ ioutil.ReadFile ব্যবহার করে ফাইলের কনটেন্ট পড়া যায়।
  • ফাইল লেখা: os.Create এবং WriteString বা সহজ ioutil.WriteFile ব্যবহার করে ফাইলে ডাটা লেখা যায়।
  • ডাটা অ্যাপেন্ড করা: os.OpenFile এর os.O_APPEND ফ্ল্যাগ দিয়ে ফাইল অ্যাপেন্ড মোডে খোলা হয় এবং নতুন কনটেন্ট ফাইলের শেষে যোগ করা হয়।
  • ফাইল ব্যবহারের শেষে ফাইল বন্ধ করার জন্য defer file.Close() ব্যবহার করতে ভুলবেন না।

এই পদ্ধতিগুলির মাধ্যমে Go তে ফাইল হ্যান্ডলিং খুব সহজ এবং কার্যকরীভাবে করা যায়।

©2025 Linux Bangla | Developed & Maintaind by Linux Bangla.