기본 콘텐츠로 건너뛰기

golang bacth processing - file to file



  go 언어 배치 프로그램중에 file to file  처리하기

 1. 파일을 오픈하여 한 라인씩 읽어서 전체 파일을 처리한다.
 2. 파일을 한 라인씩 쓴다.

3. fmt 패키지에 파일로 처리하는 모듈을 이용한다.
    -  Fprintln(출력될 구조체 버퍼, 실제 출력한 데이터)
    -  타입을 자동으로 알아서 출력한다.

func Fprintln

func Fprintln(w io.Writer, a ...interface{}) (n int, err error)


package main

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

// readLines reads a whole file into memory
// and returns a slice of its lines.
// 파일을 한 라인씩 읽기
// bufio 패키지의 scanner  구조체를 이용하여 처리한다.
// 
func readLines(path string) ([]string, error) {
    file, err := os.Open(path)
    if err != nil {
        return nil, err
    }
    defer file.Close()

    var lines []string
    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        lines = append(lines, scanner.Text())
    }
    return lines, scanner.Err()
}

// writeLines writes the lines to the given file.
// bufio를 이용하여 한 라인씩 처리한다.
//  버퍼를 만들어서 한라인씩 출력한다.



func writeLines(lines []string, path string) error {
    file, err := os.Create(path)
    if err != nil {
        return err
    }
    defer file.Close()

    w := bufio.NewWriter(file)
    for _, line := range lines {
        fmt.Fprintln(w, line)
    }
    return w.Flush()
}

func main() {
    lines, err := readLines("foo.in.txt")
    if err != nil {
        log.Fatalf("readLines: %s", err)
    }
    for i, line := range lines {
        fmt.Println(i, line)
    }

    if err := writeLines(lines, "foo.out.txt"); err != nil {
        log.Fatalf("writeLines: %s", err)
    }
}


댓글

이 블로그의 인기 게시물

golang overload 처럼 처리하기

go 언어에서는 함수명이 같을 경우 재선언 오류를 발생시킨다. 다른 메소드를 만들고 오버로드 처리하도록 설계해서 구현해야 한다. 오버로드 처리를 위해 type switch를 사용해서 들어오는 타입에 따라 메소드 호출하는 처리를 사용한다. 함수나 메소드 인자를 다양하게 처리하려면 []interface{} 로 정의해서 다양한 인자를 받아서 오버로딩 처리하면된다. package main import (  "fmt" ) func main() {  var p Person  p = Person{"dahl"}  var s string = "moon"  fmt.Println(" overloading  ", p.Overload(s))  fmt.Println(" overloading", p.Overload(nil)) } type Person struct {  name string } func (this *Person) Overload(args interface{}) string {  switch args.(type) {  case string:   return this.GetName2("moon")  case nil:   return this.GetName1()  default:   return " no match"  } } func (this *Person) GetName1() string {  return this.name } func (this *Person) GetName2(s string) string {  return this.name }

Python으로 julian date 산출하기

줄리안 일수 산출을 위해서는 윤년여부 체크를 하여 실제 그 해의 해당 일자에 대한 일수를 365 나 366 일수에 해당 일자로 전환하여 산출한다. 현재 일자를 줄리안 즉 시퀀스 일자대로 수정하는 로직이다 #일자 산출 함수 def dayconvert(month) :      convertDay = 0      dayDict = {'01':0, '02':31, '03':59, '04':90, '05':120,      '06':151, '07':181, '08':212, '09':243, '10':273,      '11':304, '12':334}      convertDay = dayDict[month]      return convertDay #줄리안데이 산출 함수 def julian(date):     year = int(date[0:4])    month = date[4:6]    day = int(date[6:8])    #윤년여부 호출   yuncheck = yunyear(year)   # 일자산출   Dday = dayconvert(month)   # 줄리안 데이 산출   Dday = Dday + day   # 유년여부 체크 및 윤년일 경우 일수조정   if yuncheck == 1:       if int(month) > 2 :            Dday = Dday + 1   # 100일 미만일 경우 포맷조정   if Dday < 100 :          Dday = '0' + str(Dday)   else :         pass   #줄리안 일자를 스트링으로 포맷 조정

Understanding golang Type . 타입이해하기...

Pre-declared Types   go 언어에서 빌드인으로 정의된 데이터 타입들.   string, number(int, uint, float...), boolean 타입들 Named vs Unnamed Type    go언어에서는 사용자 정의(type T_Int int 등)는 기본적으로 named type 으로 인식한다.   그리고  pre-declared types도 named type으로 인식한다.    unnamed type은 composited 타입들로 []int, *int 등을 별도로 인식한다.    named type 들은 메소드 정의가 가능하지만 unnamed type은 메소드를 만들 수 없다.    type Map map[string]string //this is valid func (m Map) Set(key string, value string){ m[key] = value } //this is invalid func (m map[string]string) Set(key string, value string){ m[key] = value } Underlying Type     모든 타입은 underlying type 을 가집니다.  리터럴과 declared type들은 자신의 타입을  underlying type으로 처리한다.     새로 생성되는 타입들에는 기존의 타입들이 있어야 하고 이 타입들도 항상 underlying type 을 가진다.      type Map map[string]string type SpecialMap Map SpecialMap과 Map이 underlying type은 map[string]string 이다. Assignability      //사용자 정의 타입 type Mystring string // pre-de