python中的CSV模块

python中的CSV模块,第1张

python中的CSV模块

1、查询CSV模块中都有哪些函数和功能?

① 通过dir()函数查询CSV模块都有哪些函数

import csv

for i in dir(csv):
    print(i)

② 搜索CSV模块的官方教程

’https://docs.python.org/3.6/library/csv.html‘

③ 搜索中文教材

’https://yiyibooks.cn/xx/python_352/library/csv.html#module-csv‘

2、读取CSV文件

import csv

with open("test.csv",'r',newline = '',encoding='utf-8')  as f:
    reader = csv.reader(f)
    #使用csv的reader()方法,创建一个reader对象
    for row in reader: 
    #遍历reader对象的每一行
        print(row)

3、写入CSV文件

import csv

with open('test.csv','a',newline='',encoding='utf-8') as f:
    #test.csv代表文件路径;a代表追加写入;encoding指定编码方式
    writer = csv.writer(f)  #实例化writer对象
    writer.writerow([1,2,3,4,5])
    #调用writerow方法写入一行数据
    writer.writerows([['4', '猫砂', '25', '1022', '886'],['5', '猫罐头', '18', '2234', '3121']])
    # 调用writerow方法写入多行数据

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/zaji/5711604.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存