From 5304f942a15679a0d2d8fe6c5a3071e6b3c1bd3a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=A0=E7=8C=AE=E7=BB=B4?= Date: Sat, 20 Jan 2024 21:14:18 +0800 Subject: [PATCH] =?UTF-8?q?=E5=88=97=E5=87=BA=E5=BD=93=E5=89=8D=E7=9B=AE?= =?UTF-8?q?=E5=BD=95=E7=9A=84=E6=96=87=E4=BB=B6=E5=90=8D=E7=A7=B0=EF=BC=8C?= =?UTF-8?q?=E5=B9=B6=E8=BE=93=E5=87=BA=E5=88=B0=E6=96=87=E4=BB=B6=E4=B8=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../data_func/go_to_file/demo02/main.go | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 golang_learn/data_func/go_to_file/demo02/main.go diff --git a/golang_learn/data_func/go_to_file/demo02/main.go b/golang_learn/data_func/go_to_file/demo02/main.go new file mode 100644 index 0000000..e0deff7 --- /dev/null +++ b/golang_learn/data_func/go_to_file/demo02/main.go @@ -0,0 +1,56 @@ +package main + +import ( + "encoding/csv" + "fmt" + "os" + "path/filepath" +) + +func main() { + // 获取当前目录 + dir, err := os.Getwd() + if err != nil { + fmt.Println("Error getting current directory:", err) + return + } + + // 创建 CSV 文件 + file, err := os.Create(filepath.Join(dir, "a.csv")) + if err != nil { + fmt.Println("Error creating CSV file:", err) + return + } + defer file.Close() + + // 创建 CSV writer + writer := csv.NewWriter(file) + defer writer.Flush() + + // 获取当前目录下的所有文件 + err = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { + if err != nil { + fmt.Println("Error accessing path:", err) + return nil + } + + // 忽略目录,只处理文件 + if !info.IsDir() { + // 写入文件名到 CSV + err := writer.Write([]string{info.Name()}) + if err != nil { + fmt.Println("Error writing to CSV:", err) + return err + } + } + + return nil + }) + + if err != nil { + fmt.Println("Error walking through directory:", err) + return + } + + fmt.Println("File names written to a.csv successfully.") +}