Browse Source

列出当前目录的文件名称,并输出到文件中

master
张献维 1 year ago
parent
commit
5304f942a1
  1. 56
      golang_learn/data_func/go_to_file/demo02/main.go

56
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.")
}
Loading…
Cancel
Save