[英]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 文档。 这是一种方法,还有其他方法(使用os
或bufio
)
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")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.