如何使用go脚本创建新文件

时间:2017-10-14 19:42:24

标签: go

我是新来的。我可以使用go脚本从终端创建一个新文件。像这样

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

但我想从脚本中创建文件。

package main

import "fmt"

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

3 个答案:

答案 0 :(得分:3)

如果您尝试将某些文本打印到文件中,则可以采用以下方式执行此操作,但如果该文件已存在,则其内容将丢失:

/*
|--------------------------------------------------------------------------
| Turn On The Lights
|--------------------------------------------------------------------------
|
| We need to illuminate PHP development, so let us turn on the lights.
| This bootstraps the framework and gets it ready for use, then it
| will load up this application so that we can run it and send
| the responses back to the browser and delight our users.
|
*/

$app = require_once __DIR__.'/../bootstrap/app.php';

// set the public path to this directory
$app->bind('path.public', function() {
    return __DIR__;
});

以下方法允许您附加到现有文件(如果已存在),或者创建新文件(如果该文件不存在):

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)
    }
}

答案 1 :(得分:1)

您只需查看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)
    }
}

答案 2 :(得分:0)

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

相关问题