LoginSignup
29
22

More than 5 years have passed since last update.

Go言語でファイル操作: ファイルを作って書き込む

Posted at

この記事の目的

  • Go言語でファイルに書き込めるようになる

準備

適当に作業用のディレクトリを作る:

mkdir ~/Desktop/gofile
cd ~/Desktop/gofile/

処理を書いていくGoのファイルを作ってエディタで開く:

touch main.go

ファイルに1行書き込む

ioutil.WriteFileを使うと1行でファイルの書き込みができる:

main.go
package main

import (
    "io/ioutil"
    "os"
)

func main() {
    content := []byte("hello world\n")
    ioutil.WriteFile("/tmp/go-file", content, os.ModePerm)
}

実行する:

go run main.go

書き込めているか確認:

% cat /tmp/go-file
hello world

ファイルに複数行書き込む

main.go
package main

import (
    "io/ioutil"
    "os"
)

func main() {
    content := []byte(
        "hello world\n" +
            "hello world\n" +
            "hello world\n" +
            "hello world\n",
    )
    ioutil.WriteFile("/tmp/go-file", content, os.ModePerm)
}

実行する:

go run main.go

書き込めているか確認:

% cat /tmp/go-file
hello world
hello world
hello world
hello world

Raw string literalを使って複数行書き込む

main.go
package main

import (
    "io/ioutil"
    "os"
)

func main() {
    content := []byte(
        `hello world
hello world
hello world
hello world
`)
    ioutil.WriteFile("/tmp/go-file", content, os.ModePerm)
}

実行する:

go run main.go

書き込めているか確認:

% cat /tmp/go-file
hello world
hello world
hello world
hello world
29
22
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
29
22