To read a file in Go, you can use the built-in os
and bufio
packages. Here is an example code snippet that demonstrates how to read a file line by line:
main.go652 chars34 lines
In this example, we first open the file using os.Open()
, which returns the file and an error (if any). We then create a new scanner using bufio.NewSaner()
and set the split function to bufio.ScanLines
so that the scanner reads the file line by line. We then loop through each line, printing it to the console, and finally check for any errors using scanner.Err()
. It's also important to defer the closing of the file until the end of the function using defer file.Close()
.
gistlibby LogSnag