Count the number of lines. Use the wc command for confirmation.
Go
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
//Specify the read file
name := "../hightemp.txt"
line := 0
//Open the file to read
f, err := os.Open(name)
if err != nil {
fmt.Printf("os.Open: %#v\n",err)
return
}
defer f.Close() //Crease at the end
//Create a scanner library
scanner := bufio.NewScanner(f)
//Read one line of data
for scanner.Scan() {
line++;
}
//Check if there was an error
if err = scanner.Err(); err != nil {
fmt.Printf("scanner.Err: %#v\n",err)
return
}
//Show number of lines
fmt.Println("Line",line)
}
python
import sys
line = 0
#Open file
with open("../hightemp.txt", "r") as f:
#Read line by line
for data in f:
#Add the number of lines
line += 1
#Show number of lines
print("Line",line)
Javascript
//Module loading
var fs = require("fs");
var readline = require("readline");
var line = 0;
//Create a stream
var stream = fs.createReadStream("../hightemp.txt", "utf8");
//Pass Stream to readline
var reader = readline.createInterface({ input: stream });
//Row read callback
reader.on("line", (data) => {
line = line + 1
});
//Close callback
reader.on("close", function () {
console.log("Line",line);
});
Finally, we entered "Chapter 2: UNIX Command Basics"! !! ..
I heard that I entered Chapter 2, so I finally changed the Python version setting to 3.7. It's just an IDE setting ... Find out where the settings are ... Excuse me.
While checking each language to read the file. Go, Python didn't bother me so much, Javascirpt. Oh oh. Something interesting. Is it necessary to be careful about the way of thinking because it is asynchronous?
The variable name was fname in Go language, but IDE (Golang) says typo ?. I wonder if I'm grateful. For the time being, change it to name and avoid it.
Recommended Posts