Python csv模块writer对象

使用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

相关推荐
ZhengEnCi33 分钟前
电脑操作 Agent 一直点不中:截图没更新时,提示词该怎么改才能停止瞎试
人工智能·python·agent
Wellijohn2 小时前
dict、tuple、dataclass 还是 slots?我把 6 种数据载体的 8 项开销全测了一遍
后端·python·性能优化
bufengwangluo3 小时前
爬虫和调用 API 有什么区别?为什么优先选 API
python·网络爬虫·ip·api调用
Dmz丶3 小时前
前端转 AI 100 天 Day 54:RAG 项目实战(三)——多轮对话 + 会话管理
python
console.log('npc')4 小时前
Python第9课 类学习笔记,前端js语法对照
前端·python·学习
geovindu5 小时前
python:Logistic Regression
开发语言·后端·python·算法
geovindu6 小时前
python: Random Forest
开发语言·后端·python·算法·随机森林
真上帝的左手7 小时前
2. 编程语言-Python-Anaconda
开发语言·python
aifannihao7 小时前
断言从 == 改成 > 0:用 Python 审出 git diff 里的测试降级
git·python·测试·标准库·代码审查