forked from go/golangs_learn
张献维
1 year ago
1 changed files with 56 additions and 0 deletions
@ -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…
Reference in new issue