读取csv的几种方式
有一组这样的数据:直接上代码:Python# -*- coding: utf-8 -*-"""@Time: 2018/1/26@Author: songhao@微信公众号: zeropython@File: data.py""...
·
有一组这样的数据:
直接上代码:
# -*- coding: utf-8 -*- """ @Time: 2018/1/26 @Author: songhao @微信公众号: zeropython @File: data.py """ # 导入用到的库 import csv from collections import <span class="wp_keywordlink_affiliate"><a href="https://www.168seo.cn/tag/namedtuple" title="View all posts in namedtuple" target="_blank">namedtuple</a></span> with open('data.csv', encoding="utf8") as f: f_csv = csv.reader(f) # 获取csv 表头 headings = next(f_csv) # 映射名称到序列元素 Row = <span class="wp_keywordlink_affiliate"><a href="https://www.168seo.cn/tag/namedtuple" title="View all posts in namedtuple" target="_blank">namedtuple</a></span>('Row', headings) print("表头",headings) for r in f_csv: row = Row(*r) print(row) # 可以直接根据下标进行访问 print(row.支付订单数) """ # 另外一个选择就是将数据读取到一个字典序列中去。可以这样做: import csv with open('data.csv', encoding="utf-8") as f: # f_csv = csv.reader(f) # header = next(f_csv) f_csv = csv.DictReader(f) # print(header) datas = [] for row in f_csv: print(row.keys()) datas.append(row) # 是一个字典的类型 print(isinstance(row,dict)) print(row['支付订单数']) /usr/local/bin/python3.6 /Users/songhao/Desktop/data/data.py odict_keys(['买家ID', '支付订单数', '客单价', '退货订单数']) True 2 with open('data2.csv', 'w',encoding='utf-8') as f: # 创建一个 writer 对象 f_csv = csv.writer(f) # 写入数据源 f_csv.writerows(datas) """
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
# -*- coding: utf-8 -*-
"""
@Time: 2018/1/26
@Author: songhao
@微信公众号: zeropython
@File: data.py
"""
# 导入用到的库
import
csv
from
collections
import
namedtuple
with
open
(
'data.csv'
,
encoding
=
"utf8"
)
as
f
:
f_csv
=
csv
.
reader
(
f
)
# 获取csv 表头
headings
=
next
(
f_csv
)
# 映射名称到序列元素
Row
=
namedtuple
(
'Row'
,
headings
)
print
(
"表头"
,
headings
)
for
r
in
f_csv
:
row
=
Row
(
*
r
)
print
(
row
)
# 可以直接根据下标进行访问
print
(
row
.支付订单数
)
"""
# 另外一个选择就是将数据读取到一个字典序列中去。可以这样做:
import csv
with open('data.csv', encoding="utf-8") as f:
# f_csv = csv.reader(f)
# header = next(f_csv)
f_csv = csv.DictReader(f)
# print(header)
datas = []
for row in f_csv:
print(row.keys())
datas.append(row)
# 是一个字典的类型
print(isinstance(row,dict))
print(row['支付订单数'])
/usr/local/bin/python3.6 /Users/songhao/Desktop/data/data.py
odict_keys(['买家ID', '支付订单数', '客单价', '退货订单数'])
True
2
with open('data2.csv', 'w',encoding='utf-8') as f:
# 创建一个 writer 对象
f_csv = csv.writer(f)
# 写入数据源
f_csv.writerows(datas)
"""
|
更多推荐
已为社区贡献9条内容
所有评论(0)