[JAVA] 13. Merge col1.txt and col2.txt

13. Merge col1.txt and col2.txt

Combine the col1.txt and col2.txt created in 12, and create a text file in which the first and second columns of the original file are arranged by tab delimiters. Use the paste command for confirmation.

Go

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	//Specify the read file
	wname := "col.txt"
	r1name := "col1.txt"
	r2name := "col2.txt"

	//Open the file to read
	w, err := os.Create(wname)
	if err != nil {
		fmt.Printf("os.Open: %#v\n",err)
		return
	}
	defer w.Close() //Crease at the end

	//Create a save file for the first column
	r1, err := os.Open(r1name)
	if err != nil {
		fmt.Printf("os.Open: %#v\n",err)
		return
	}
	defer r1.Close() //Crease at the end

	//Create a second column save file
	r2, err := os.Open(r2name)
	if err != nil {
		fmt.Printf("os.Open: %#v\n",err)
		return
	}
	defer r2.Close() //Crease at the end

	//Create a scanner library
	scanner1 := bufio.NewScanner(r1)
	scanner2 := bufio.NewScanner(r2)

	//Read one line of data
	for scanner1.Scan() {
		scanner2.Scan()
		w.WriteString(scanner1.Text() + "\t" + scanner2.Text() + "\n")
	}

	//Check if there was an error
	if err = scanner1.Err(); err != nil {
		fmt.Printf("scanner1.Err: %#v\n",err)
		return
	}

	//Check if there was an error
	if err = scanner2.Err(); err != nil {
		fmt.Printf("scanner2.Err: %#v\n",err)
		return
	}
}

python

#Open the output file
with open("col.txt", "w") as w:
    #Open the first read file
    with open("col1.txt", "r") as r1:
        #Open the second read file
        with open("col2.txt", "r") as r2:
            #Read line by line
            for data1 in r1:
                #Read the second file
                data2 = r2.readline()

                # col1.txt data and col2.txt data separated by TAB col.Output to txt
                w.writelines(data1.strip() + "\t" + data2.strip() + "\n")

Javascript

//Module loading
var fs = require("fs");
var col = [];

//  col1.txt,col2.Read txt text file
var col1Text = fs.readFileSync("col1.txt", 'utf-8');
var col2Text = fs.readFileSync("col2.txt", 'utf-8');

//Split a string with a line break
var col1 = col1Text.split('\n');
var col2 = col2Text.split('\n');

//Item count loop
for (i=0;i<col1.length;i++) {
    //Combine items separated by TAB
    col.push(col1[i] + "\t" + col2[i]);
}

//  col.Output text concatenated with line breaks to txt
fs.writeFileSync("col.txt",col.join('\n'));

Summary

Javascript This is all written in buffer processing. When processing 3 files, the source is not refreshing ... but the output is 2 and the feeling of moodyness increases.

Top

Recommended Posts

13. Merge col1.txt and col2.txt
About _ and __
12. Save the first column in col1.txt and the second column in col2.txt