In this section, we're going to see how to count the lines of a file. Consider that we have a file and it has a bunch of names in each line, and we have to count how many lines there are in the file. First, we will open our file using the os.Open
package and the name of our file will be names.txt
. It returns an error, but for this example, we're not going to care about the error because we know that the file exists. So, I'm going to use a file scanner to scan the file. We have the bufio.NewScanner
package that has the new scanner and it accepts a reader so we can pass the file. The line count will start from 0
and we are going to do this for fileScanner.scan
. Thus, as long as it scans, it will increment the line count. Finally, we're going to write the number of the line to the console. Of course, when everything is done, we will use the defer file.Close()
function. Let's check the code:
package main import ( "os" "bufio" "fmt" ) func main() { file, _ := os...