使用wrie对象创建csv文件信息
python
import csv
import random
# 按行写入数据
outputFile = open("319.csv",'w',newline='',encoding='gbk') # 打开csv文件,指定编码GBK
outputWrite = csv.writer(outputFile) # 创建一个writer对象
outputWrite.writerow(['序号','姓名','书籍']) # 写入行使用list列表
outputWrite.writerow(['1','孙悟空','西游记'])
outputWrite.writerow(['2','白骨精','西游记'])
outputWrite.writerow(['3','张飞','三国演义'])
outputWrite.writerow(['4','曹操','三国演义'])
outputWrite.writerow(['5','马谡','三国演义'])
outputFile.close() # 关闭文件
# 按行输入随机数,每一行输入6个随机数
numbersFile = open("numbers.csv",'w',newline='')
numbersWrite = csv.writer(numbersFile)
numbersWrite.writerow(['随机数','1','2','3','4','5','6'])
row = int(input("请输出行数")) # 输入产生随机数行数
for i in range(row):
a = i + 1 # 序号
b = random.randint(1,10) # 随机数1~10
c = random.randint(1, 10)
d = random.randint(1, 10)
e = random.randint(1, 10)
f = random.randint(1, 10)
g = random.randint(1, 10)
numbersWrite.writerow([f'{a}',f'{b}',f'{c}',f'{d}',f'{e}',f'{f}',f'{g}']) # 将随机数插入文件
numbersFile.close()
第一个csv文件
第二个csv文件,行数20