Reading Files in Go

Go: Reading Files

Reading files in Go involves several steps:

1.Opening the file:

First, you need to open the file that you want to read. You can use the built-in function os.Open() to open a file. This function takes a file name as input and returns a pointer to a File struct, which represents the opened file.

2.Checking for errors:

It's always a good practice to check if there were any errors while opening the file. You can use the if err != nil pattern to check for errors and handle them appropriately.

3.Reading the file:

Once the file is opened, you can read its contents. You can use the bufio.NewReader() function to create a new reader object that can read from the file. Then, you can use the ReadString() or ReadLine() method of the reader object to read the file contents.

4.Closing the file:

After you have finished reading the file, it's important to close it. You can use the Close() method of the File struct to close the file.

Here's an example code snippet that demonstrates how to read a file in Go:

    package main

    import (

    func main() {
        file, err := os.Open("filename.txt")
        if err != nil {
            fmt.Println("Error:", err)
        defer file.Close()

        scanner := bufio.NewScanner(file)
        for scanner.Scan() {

        if err := scanner.Err(); err != nil {
            fmt.Println("Error:", err)
  • In above example, the os.Open() function is used to open the file "filename.txt". If there is an error while opening the file, it is handled by printing the error message and returning from the function. The defer keyword is used to ensure that the file is closed after the function has finished executing.
  • A new Scanner object is created using the bufio.NewScanner() function, which can read from the opened file. The for loop reads each line of the file using the Scan() method of the Scanner object and prints it to the console using fmt.Println().

Finally, any errors that occurred while reading the file are checked using the scanner.Err() method and handled appropriately.

Previous Article

Next Article