0
我是新郎朗。我可以使用go腳本從終端創建一個新文件。像這樣如何用go腳本創建新文件
go run ../myscript.go > ../filename.txt
但我想從腳本創建文件。
package main
import "fmt"
func main() {
fmt.Println("Hello") > filename.txt
}
我是新郎朗。我可以使用go腳本從終端創建一個新文件。像這樣如何用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)
}
}