在Go语言中,可以使用encoding/csv
包来处理CSV文件的读写操作。要同时写入两个不同的CSV文件,可以按照以下步骤进行:
encoding/csv
包和os
包:import (
"encoding/csv"
"os"
)
file1, err := os.Create("file1.csv")
if err != nil {
panic(err)
}
defer file1.Close()
file2, err := os.Create("file2.csv")
if err != nil {
panic(err)
}
defer file2.Close()
writer1 := csv.NewWriter(file1)
defer writer1.Flush()
writer2 := csv.NewWriter(file2)
defer writer2.Flush()
data1 := [][]string{
{"1", "John", "Doe"},
{"2", "Jane", "Smith"},
}
data2 := [][]string{
{"A", "Apple"},
{"B", "Banana"},
}
for _, row := range data1 {
err := writer1.Write(row)
if err != nil {
panic(err)
}
}
for _, row := range data2 {
err := writer2.Write(row)
if err != nil {
panic(err)
}
}
Flush
方法确保所有数据都被写入文件:writer1.Flush()
writer2.Flush()
完整的示例代码如下:
package main
import (
"encoding/csv"
"os"
)
func main() {
file1, err := os.Create("file1.csv")
if err != nil {
panic(err)
}
defer file1.Close()
file2, err := os.Create("file2.csv")
if err != nil {
panic(err)
}
defer file2.Close()
writer1 := csv.NewWriter(file1)
defer writer1.Flush()
writer2 := csv.NewWriter(file2)
defer writer2.Flush()
data1 := [][]string{
{"1", "John", "Doe"},
{"2", "Jane", "Smith"},
}
data2 := [][]string{
{"A", "Apple"},
{"B", "Banana"},
}
for _, row := range data1 {
err := writer1.Write(row)
if err != nil {
panic(err)
}
}
for _, row := range data2 {
err := writer2.Write(row)
if err != nil {
panic(err)
}
}
writer1.Flush()
writer2.Flush()
}
这样,就可以同时将数据写入到两个不同的CSV文件中了。请注意,示例代码中的文件名为"file1.csv"和"file2.csv",你可以根据实际需求修改文件名和路径。
领取专属 10元无门槛券
手把手带您无忧上云