首先,需要导入csv模块:
import csv
然后,可以使用open函数打开一个文件,mode参数设置为"w"表示将文件打开以写入模式:
with open('example.csv', 'w', newline='') as csvfile:
其中,'example.csv'是要写入的文件名,'w'是写入模式,newline=''是为了避免在写入文件时出现空行。
接下来,可以使用csv.writer对象来写入数据:
writer = csv.writer(csvfile)
然后,可以使用writerows方法将数据写入到文件中:
data = [['Name', 'Age'], ['John', 20], ['Alice', 25]]
writer.writerows(data)
在上面的代码中,我们首先定义了一个数据列表data,其中包含了两行数据:['Name', 'Age']和['John', 20],['Alice', 25]。然后,我们使用writerows方法将数据写入到文件中。
最后,可以使用close方法关闭文件:
with open('example.csv', 'w', newline='') as csvfile:
完整的代码如下:
import csv
with open('example.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
data = [['Name', 'Age'], ['John', 20], ['Alice', 25]]
writer.writerows(data)
csvfile.close()
运行该代码后,会生成一个名为"example.csv"的文件,其中包含了我们写入的数据。
需要注意的是,在写入数据时,csv模块会自动将数据转换为字符串,因此如果你的数据是列表或字典,这些数据将被转换为字符串。
评论 (0)