python之csv模块学习

import csv
# 读取字符串
for row in csv.reader(['one,two,three']):
    print(row)  # ['one', 'two', 'three'] 

# 写数据
with open('test_csv_data.csv', 'w', newline='') as f:
     writer = csv.writer(f, delimiter=' ',quotechar='|', quoting=csv.QUOTE_MINIMAL)
     writer.writerow(['My name is','Tom', 'Bob', 'Jim', 'May'])
     writer.writerow(['Color is', 'red', 'yellow green','blue'])

# 读数据
with open('test_csv_data.csv', newline='') as f:
    spamreader = csv.reader(f, delimiter=' ', quotechar='|')
    for row in spamreader:
        print(', '.join(row))

# My name is, Tom, Bob, Jim, May
# Color is, red, yellow green, blue

# 写入csv文件  writer.writerow和writer.writerows

with open('csv_test1.csv', 'w', newline='') as f:  # 如不指定newline='',有时则每写入一行,将有一空行被写入
    writer = csv.writer(f)
    writer.writerow(['name', 'age', 'tel'])  # 写入一行用writerow

with open('csv_test2.csv', 'w', newline='') as f:  # 如不指定newline='',有时则每写入一行,将有一空行被写入
    writer = csv.writer(f)
    data = [('Tom', '25', '1367890900'), ('Jim', '18', '1367890800')]
    writer.writerows(data)  # 多行用writerows
#
# 读取csv文件
with open('csv_test1.csv', encoding='utf-8') as f:
    csv_reader = csv.reader(f)
    for row in csv_reader:
        print(row)

with open('csv_test2.csv', encoding='utf-8') as f:
    csv_reader = csv.reader(f)
    for row in csv_reader:
        print(row)

# ['name', 'age', 'tel']
# ['Tom', '25', '1367890900']
# ['Jim', '18', '1367890800'] 

# 以字典方式写入csv 并读取csv
datas = [{'name': 'Bob', 'age': 23}, {'name': 'Jerry', 'age': 44}, {'name': 'Tom', 'age': 15}]
## 以字典方式写入csv
with open('test_csv_data.csv', 'w', newline='') as f:
    writer = csv.DictWriter(f, ['name', 'age'])  # 标头在这里传入,作为第一行数据
    writer.writeheader()
    for row in datas:
        writer.writerow(row)
        # 还可以写入多行
        writer.writerows(datas)

## 以字典方式读取csv
with open('test_csv_data.csv', 'r') as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row['name'], row['age'])

# name age
# Bob 23
# Jerry 44
# Tom 15
# Bob 23
# Jerry 44
# Tom 15 

# 捕获和报告错误: 
import csv, sys
filename = 'test_csv_data.csv'
with open(filename, newline='') as f:
    reader = csv.reader(f)
    try:
        for row in reader:
            print(row)
    except csv.Error as e:
        sys.exit('file {}, line {}: {}'.format(filename, reader.line_num, e))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值