簡體   English   中英

如何使用go腳本創建新文件

[英]How to create new file using go script

我是新來的。 我可以使用 go 腳本從終端創建一個新文件。 像這樣

go run ../myscript.go > ../filename.txt

但我想從腳本創建文件。

package main

import "fmt"

func main() {
    fmt.Println("Hello") > filename.txt
}

如果您嘗試將一些文本打印到文件中,一種方法如下所示,但是如果文件已經存在,其內容將丟失:

package main

import (
    "fmt"
    "io/ioutil"
)

func main() {
    err := ioutil.WriteFile("filename.txt", []byte("Hello"), 0755)
    if err != nil {
        fmt.Printf("Unable to write file: %v", err)
    }
}

以下方式將允許您附加到現有文件(如果它已經存在),或者如果它不存在則創建一個新文件:

package main

import (
    "os"
    "log"
)


func main() {
    // If the file doesn't exist, create it, or append to the file
    f, err := os.OpenFile("access.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
    if err != nil {
        log.Fatal(err)
    }

    _, err = f.Write([]byte("Hello"))
    if err != nil {
        log.Fatal(err)
    }

    f.Close()
}

你只需要檢查 API 文檔。 這是一種方法,還有其他方法(使用osbufio

package main

import (
    "io/ioutil"
)

func main() {
    // read the whole file at once
    b, err := ioutil.ReadFile("input.txt")
    if err != nil {
        panic(err)
    }

    // write the whole body at once
    err = ioutil.WriteFile("output.txt", b, 0644)
    if err != nil {
        panic(err)
    }
}

Fprintln非常接近你想要做的:

package main

import (
   "fmt"
   "os"
)

func main() {
   f, e := os.Create("filename.txt")
   if e != nil {
      panic(e)
   }
   defer f.Close()
   fmt.Fprintln(f, "Hello")
}

https://golang.org/pkg/fmt#Fprintln

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM