Python–cookbook–6.数据编码与处理

Python–cookbook–6.数据编码与处理

导入对应模块

import csv
from collections import namedtuple, OrderedDict
import json
from urllib.request import urlopen
import xml.etree.ElementTree as ET
from lxml import etree

读取csv

# 读取到列表或元组上去
# with open('stock.csv') as f:
#     f_csv = csv.reader(f)
#     headings = next(f_csv)  # 得到头部
#     Row = namedtuple('Row', headings)
#     for r in f_csv:
#         # print(r)  # r是每行元素列表
#         row = Row(*r)  # 转换成具名元组
#         print(row)
# 读取到字典序列中去
# with open('stock.csv') as f:
#     f_csv = csv.DictReader(f)
#     for row in f_csv:
#         print(row)  # 转换成字典

写入csv

# 列表或元组写入csv
headers = ['Symbol', 'Price', 'Date', 'Time', 'Change', 'Volume']
rows = [('AA', 39.48, '6/11/2007', '9:36am', -0.18, 181800),
        ('AIG', 71.38, '6/11/2007', '9:36am', -0.15, 195500),
        ('AXP', 62.58, '6/11/2007', '9:36am', -0.46, 935000),
        ]
row_dic = [{'Symbol': 'AA', 'Price': 39.48, 'Date': '6/11/2007',
            'Time': '9:36am', 'Change': -0.18, 'Volume': 181800},
           {'Symbol': 'AIG', 'Price': 71.38, 'Date': '6/11/2007',
            'Time': '9:36am', 'Change': -0.15, 'Volume': 195500},
           {'Symbol': 'AXP', 'Price': 62.58, 'Date': '6/11/2007',
            'Time': '9:36am', 'Change': -0.46, 'Volume': 935000},
           ]
# with open('stocks_write.csv', 'w', newline='') as f:  # newline避免空行
#     f_csv = csv.writer(f)  # 直接写
#     f_csv.writerow(headers)
#     f_csv.writerows(rows)
# with open('stocks_write.csv', 'w', newline='') as f:
#     f_csv = csv.DictWriter(f, headers)  # 写字典
#     f_csv.writeheader()
#     f_csv.writerows(row_dic)

读写JSON数据

data = {'name': 'ACME', 'shares': 100, 'price': 542.23}
# 编码和解码JSON数据其中两个主要的函数是json.dumps()和json.loads()
json_str = json.dumps(data)
data_copy = json.loads(json_str)
# print(json_str, type(json_str))
# print(data_copy, type(data_copy))

处理json文件,使用json.dump()和json.load()

# with open('data.json', 'w') as f:
#     json.dump(data, f)
# with open('data.json', 'r') as f:
#     data_new = json.load(f)
#     print(data_new)

# JSON 编码的格式对于 Python 语法而已几乎是完全一样的
# 除了一些小的差异之外,比如True 会被映射为 true,False 被映射为 false,而 None 会被映射为 null
d = {'a': True, 'b': 'Hello', 'c': None}
print(json.dumps(d))

# 保存为其他对象
# object_pairs_hook  object_hook
# data_ord = json.loads(json_str, object_pairs_hook=OrderedDict)
# print(data)

解析简单的XML数据

# u = urlopen('http://planet.python.org/rss20.xml')
# doc = parse(u)
# for item in doc.iterfind('channel/item'):
#     title = item.findtext('title')
#     date = item.findtext('pubDate')
#     link = item.findtext('link')
#     print(title)
#     print(date)
#     print(link)
#     print()

# tree = ET.parse('hopt.xml')  # ET报错
tree = etree.parse('hopt.xml')
root = tree.getroot()
print(root.note)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

柴寺仓

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值