Python
Python入门系列
Python字典
Python语法
Python代码规范与命名规则
uWSGI和WSGI之间的关系
Python字符编码
Python正则表达式
Python异常处理
Python循环控制
Python文件读写操作
Python模块和函数
Python类
Python格式处理
Python单元测试
Pythonweb采集
python的jQuery-Ajax使用
python的日志
Python变量-字符-数字
Python数组-元祖-字典-集合
Python输入输出
Python安装部署
centos下使用yum安装pip
Python原理说明
Python服务维护
Python模块
Python常用方法
Python新闻
Python使用案例
socket实现客户端和服务端
python射击游戏
将json转换成execl
Python连接Mysql测试
python发送文件
窗口实例化
Python_小说下载脚本
python代码编写规范
本文档使用 MrDoc 发布
-
+
home page
Python格式处理
[TOC] ### 一.CVS表格 ```python 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) #读取cvs with open('villains', 'rt') as fin: # 一个上下文管理器 cin = csv.reader(fin) villains = [row for row in cin] # 使用列表推导式 print(villains) #读取成字典方式 with open('villains', 'rt') as fin: cin = csv.DictReader(fin, fieldnames=['first', 'last']) villains = [row for row in cin] #将字典写入成标题在上面的方式 villains = [ {'first': 'Doctor', 'last': 'No'}, {'first': 'Rosa', 'last': 'Klebb'}, {'first': 'Mister', 'last': 'Big'}, {'first': 'Auric', 'last': 'Goldfinger'}, {'first': 'Ernst', 'last': 'Blofeld'}, ] with open('villains', 'wt') as fout: cout = csv.DictWriter(fout, ['first', 'last']) cout.writeheader() cout.writerows(villains) with open('villains', 'rt') as fin: #重头读取文件 cin = csv.DictReader(fin) villains = [row for row in cin] ``` ### 二.xml menu.xml ```python <?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> ``` ```python import xml.etree.ElementTree as et tree = et.ElementTree(file='menu.xml') root = tree.getroot() root.tag #tag是标签字符串,attrib是属性的一个字典 for child in root: print('tag:', child.tag, 'attributes:', child.attrib) for grandchild in child: print('\ttag:', grandchild.tag, 'attributes:', grandchild.attrib) len(root) #菜单选择数目 len(roo[0]) #早餐项的数目 ``` ### 三.json json字符串 ```python 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" } } } ``` ```python import json menu_json = json.dumps(menu) menu_json menu2 = json.loads(menu_json) #解析成python结构 import datetime now = datetime.datetime.utcnow() json.dumps(now) #无法转换,因为标准json没有定义日期 #转换 now_str = str(now) json.dumps(now_str) #可以转换了 from time import mktime now_epoch = int(mktime(now.timetuple())) json.dumps(now_epoch) #可以转换epoch值 class DTEncoder(json.JSONEncoder): #继承重载default方法 def default(self, obj): # isinstance()检查obj的类型 if isinstance(obj, datetime.datetime): return int(mktime(obj.timetuple())) # 否则是普通解码器知道的东西: return json.JSONEncoder.default(self, obj) json.dumps(now, cls=DTEncoder) ``` ### 四.yml ```python import yaml with open('mcintyre.yaml', 'rt') as fin: text = fin.read() data = yaml.load(text) data['details'] len(data['poems']) data['poems'][1]['title'] #获得第二行 ``` ### 五.配置文件 ```python [english] greeting = Hello [french] greeting = Bonjour [files] home = /usr/local # 简单的插入: bin = %(home)s/bin ``` ```python import configparser cfg = configparser.ConfigParser() cfg.read('settings.cfg') cfg['french'] cfg['french']['greeting'] cfg['files']['bin'] #返回节点列表 config.sections() #指定节点下的 config.options(section) ``` ### 六.数据库 ```python 连接数据库,包含参数用户名、密码、服务器地址 connect() 创建一个cursor对象来管理查询 cursor() 对数据库执行一个或多个SQL命令 execute() 和 executemany() 得到execute之后的结果 fetchone()、fetchmany() 和 fetchall() import sqlite3 conn = sqlite3.connect('enterprise.db') curs = conn.cursor() curs.execute('''CREATE TABLE zoo (critter VARCHAR(20) PRIMARY KEY, count INT, damages FLOAT)''') curs.execute('INSERT INTO zoo VALUES("duck", 5, 0.0)') #新增动物 curs.execute('INSERT INTO zoo VALUES("bear", 2, 1000.0)') ins = 'INSERT INTO zoo (critter, count, damages) VALUES(?, ?, ?)' curs.execute(ins, ('weasel', 1, 2000.0)) #更安全的插入数据方法 curs.execute('SELECT * FROM zoo') #获取数据 curs.fetchall() curs.execute('SELECT * from zoo ORDER BY count') #按照count排序 curs.fetchall() curs.execute('''SELECT * FROM zoo WHERE #哪种动物花费最多 damages = (SELECT MAX(damages) FROM zoo)''') curs.close() #打开后要关闭 ``` 
日行一善
April 23, 2021, 8:54 a.m.
Share documents
Collection documents
Last
Next
Scan wechat
Copy link
Scan your mobile phone to share
Copy link
关于 MrDoc
觅思文档MrDoc
是
州的先生
开发并开源的在线文档系统,其适合作为个人和小型团队的云笔记、文档和知识库管理工具。
如果觅思文档给你或你的团队带来了帮助,欢迎对作者进行一些打赏捐助,这将有力支持作者持续投入精力更新和维护觅思文档,感谢你的捐助!
>>>捐助鸣谢列表
微信
支付宝
QQ
PayPal
QQ粉丝交流群:882382311
Markdown文件
share
link
type
password
Update password