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.") +}