Python 各种格式文件转换

Python 各种格式文件转换

  • txt文本文件
  • csv文件
  • xml文件
  • html文件
  • json文件
  • yaml文件
  • properties文件
  • ini/cfg文件
  • xml文件
一、CSV
  1. 写入csv文件
import csv
villains = [
    ['Doctor', 'No'],
    ['Rosa', 'Klebb'],
    ['Mister', 'Big'],
    ['Auric', 'Goldfinger'],
    ['Ernst', 'Blofeld']
]
with open('villains', 'wt') as fout:
    csvout = csv.writer(fout)
    csvout.writerows(villains)
  1. 读取csv文件
# 读取csv文件
import csv
with open('villains', 'rt') as fin:
    cin = csv.reader(fin)
    villains = [row for row in cin]

print(villains)
  1. 使用DictWriter指定列名
import csv
villains = [
    {'first': 'Doctor', 'last': 'No'},
    {'first': 'Rosa', 'last': 'Klebb'},
    {'first': 'Mister', 'last': 'Big'},
    {'first': 'Auric', 'last': 'Goldfinger'},
    {'first': 'Ernst', 'last': 'Blofeld'}
]
with open('villains.txt', 'wt') as fout:
    cout = csv.DictWriter(fout, ['first', 'last'])
    cout.writeheader()
    cout.writerows(villains)
  1. 使用DictReader指定列名
# 读取csv文件
import csv
with open('villains', 'rt') as fin:
    cin = csv.DictReader(fin, fieldnames=['first', 'last'])
    villains = [row for row in cin]

print(villains)
二、XML

menu.xml

<?xml version="1.0"?>
<menu>
	<breakfast hours="7-11">
  	<item price="$6.00">breakfast burritos</item>
    <item price="$4.00">pancakes</item>
  </breakfast>
  <lunch hours="11-3">
  	<item price="$5.00">hamburger</item>
  </lunch>
  <dinner hours="3-10">
  	<item price="$8.00">spaghetti</item>
  </dinner>
</menu>

使用标准库ElementTree解析menu.xml

import xml.etree.ElementTree as et
tree = et.ElementTree(file='menu.xml')
root = tree.getroot()
print(root.tag)
for child in root:
  print('tag:', child.tag, ',attributes', child.attrib)
  for gradchild in child:
    print('\ttag:', gradchild.tag, ',attributes:', gradchild.attrib)

xml第三方库

xml.dom:将整个xml载入内存读取。

Xml.sax:动态解析xml,不用一次性载入内存。

三、HTML

使用Flask、Django等Web框架和jinja2等模版渲染引擎向浏览器渲染html文件内容。

四、JSON

python字典转换为json字符串

menu = {
    "breakfast": {
        "hours": "7-11",
        "items": {
            "breakfast burritos": "$6.00",
            "pancakes": "$4.00"
        }
    },
    "lunch": {
        "hours": "11-3",
        "items": {
            "hamburger": "$5.00"
        }
    },
    "dinner": {
        "hours": "3-10",
        "items": {
            "spaghetti": "$8.00"
        }
    }
}

import json
menu_json = json.dumps(menu)
print(menu_json)

json字符串转换为python字典

menus = '{"breakfast": {"hours": "7-11", "items": {"breakfast burritos": "$6.00", "pancakes": "$4.00"}}, "lunch": {"hours": "11-3", "items": {"hamburger": "$5.00"}}, "dinner": {"hours": "3-10", "items": {"spaghetti": "$8.00"}}}'
menu2 = json.loads(menus)
print(menu2)

关于datetime类型

import datetime
import json 
now = datetime.datetime.utcnow()
json.dumps(now, default=str)
五、YAML

Python标准库尚未包含yaml相关的库进行操作,需要使用第三方库yaml。

mcintyre.yml

name:
	first: James
	last: McIntyre
dates:
	birth: 1828-05-25
	death: 1906-03-31
details:
	bearded: true
	themes: [cheese, Canada]
poems:
	- title: 'Motto'
		text: |
			Politeness, perseverance and pluck,
			To their possessor will bring good luck
	- title: 'Canadian Charms'
		text: |
			Here industry is not in vain,
			For we hava bounteous crops of grain
			And you behold on every field Of grass and roots abundant yield,
			But after all the greatest charm
			
			Is the snug home upon the farm,
			And stone walls now keep cattle warm.

加载yaml

import yaml
with open('mcintyre.yaml', 'rt') as fin:
    text = fin.read()
data = yaml.safe_load(text, Loader=yaml.FullLoader)
print(data)
六、tablib

tablib可以处理CSV、JSON、YAML格式的表格数据,以及Microsoft Excel、Pandas DataFrame等一些其他格式

$ pip install tablib
七、Pandas

Pandas是用于结构化数据的Python库,可作为处理显示数据问题的绝佳工具。

  • 读写多种文本和二进制文件格式

  • CSV格式

  • 固定宽度文本

  • Excel

  • JSON

  • HTML

  • SQL

  • HDF5

  • 其他

  • 分组、分割、合并、索引、切片、排序、选择、标记

  • 转换数据类型

  • 修改大小或塑形

  • 处理丢失的数据

  • 生成随机值

  • 管理时间序列

read函数会返回DataFrame对象,这是Pandas对于二维数据(行和列)的标准表示,在某些方面类似于电子表格或关系数据库表,对于一维数据Pandas使用Series对象表示。

读取csv
import pandas
data = pandas.read_csv('villains.txt')
print(data)

变量data就是一个DataFrame对象,它特别适用于使用NumPy进行繁重的数值运算以及机器学习的数据准备。

八、ini/cfg配置文件

使用标准模块configparser可以处理.ini文件。

settings.cfg

[english]
greeting = Hello
[french]
greeting = Bonjour
[files]
home = /usr/local
bin = %(home)s/bin

读取ini文件

import configparser
cfg = configparser.ConfigParser()
cfg.read('settings.cfg')
print(cfg)
九、Microsoft Excel

用于操作Microsoft Excel的第三方库有xlrd、tablib、python-excel、xlwt、xlutils等。

使用pandas读取Microsoft Excel

import pandas as pd
# 读取本地excel文件
data = pd.read_excel(r"/home/text.xlsx", sheet_name="data", sheet_index = 1, header = 0)

data为Pandas的DataFrame对象。

pandas写入Microsoft Excel

import pandas as pd
data = { 'name': ['zs', 'ls', 'ww'], 'age': [11, 12, 13], 'gender': ['man', 'man', 'woman']}
# 将数据转化为DataFrame格式
dataframe = pd.DataFrame(data)
# 写入本地excel文件
dataframe.to_excel("/home/text.xlsx" , sheet_name="data", na_rep="na_test",header=0)
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值