猿问

如何使用文件名创建切片

有一个每秒创建文件的程序。我想将文件名附加到切片中并打印出来。现在我的程序执行不正确,它附加名称但仅用于一个文件名。所以我希望得到[]string{"1","2","3"},而不是我得到[]string{"1","1","1"},[]string{"2","2","2"}, []string{"3","3","3"}。如何更正我的程序以获得预期结果?


package main


import (

    "encoding/csv"

    "fmt"

    "os"

    "strconv"

    "time"

)


func main() {

    for {

        time.Sleep(1 * time.Second)

        createFile()

    }

}


func createFile() {

    rowFile := time.Now().Second()

    fileName := strconv.Itoa(rowFile)

    file, err := os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)

    if err != nil {

        fmt.Println(err)

    }

    defer file.Close()


    writer := csv.NewWriter(file)

    writer.Comma = '|'


    err = writer.Write([]string{""})

    if err != nil {

        fmt.Println(err)

    }

    countFiles(fileName)

}


func countFiles(fileName string) {

    arrFiles := make([]string, 0, 3)

    for i := 0; i < 3; i++ {

        arrFiles = append(arrFiles, fileName)

    }

    fmt.Println(arrFiles)// here I expect ["1","2","3"] then ["4","5","6"] and so on. But now there is ["1","1","1"] then ["2","2","2"] and so on

}


HUH函数
浏览 125回答 1
1回答

FFIVE

createFile()不会以任何方式保留创建的文件名。你可以这样做:&nbsp;package mainimport (&nbsp; &nbsp; "encoding/csv"&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "os"&nbsp; &nbsp; "strconv"&nbsp; &nbsp; "time")func main() {&nbsp; &nbsp; files := []string{}&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; time.Sleep(1 * time.Second)&nbsp; &nbsp; &nbsp; &nbsp; files = append(files, createFile())&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(files)&nbsp; &nbsp; }}func createFile() string {&nbsp; &nbsp; rowFile := time.Now().Second()&nbsp; &nbsp; fileName := strconv.Itoa(rowFile)&nbsp; &nbsp; file, err := os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(err)&nbsp; &nbsp; }&nbsp; &nbsp; defer file.Close()&nbsp; &nbsp; writer := csv.NewWriter(file)&nbsp; &nbsp; writer.Comma = '|'&nbsp; &nbsp; err = writer.Write([]string{""})&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(err)&nbsp; &nbsp; }&nbsp; &nbsp; return fileName}
随时随地看视频慕课网APP

相关分类

Go
我要回答