我是新来的语言。我可以使用 go 脚本从终端创建一个新文件。像这样
go run ../myscript.go > ../filename.txt
但我想从脚本创建文件。
package main
import "fmt"
func main() {
fmt.Println("Hello") > filename.txt
}
如果您尝试将一些文本打印到文件中,一种方法如下所示,但是如果文件已经存在,则其内容将丢失:
package main
import (
"fmt"
"os"
)
func main() {
err := os.WriteFile("filename.txt", []byte("Hello"), 0755)
if err != nil {
fmt.Printf("Unable to write file: %w", 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")
}