python 自动化之路 day 03
内容目录:
1. 字典
2. 集合
3. 文件处理
1、 字典操作
字典一种key - value 的数据类型,使用就像我们上学用的字典,通过笔划、字母来查对应页的详细内容。
语法:
info = {
'stu1101': "TengLan Wu",
'stu1102': "LongZe Luola",
'stu1103': "XiaoZe Maliya",
}
字典的特性:
- dict是无序的
- key必须是唯一的,so 天生去重
增加
修改
删除
查找
多级字典嵌套及操作
其它姿势
循环dict

#方法1
for key in info:
print(key,info[key]) #方法2
for k,v in info.items(): #会先把dict转成list,数据里大时莫用
print(k,v)

程序练习
程序: 三级菜单
要求:
- 打印省、市、县三级菜单
- 可返回上一级
- 可随时退出程序
2、集合操作
集合是一个无序的,不重复的数据组合,它的主要作用如下:
- 去重,把一个列表变成集合,就自动去重了
- 关系测试,测试两组数据之前的交集、差集、并集等关系
常用操作
3、文件操作
对文件操作流程
- 打开文件,得到文件句柄并赋值给一个变量
- 通过句柄对文件进行操作
- 关闭文件
现有文件如下
基本操作
1
2
3
4
5
6
7
8
|
f = open ( 'lyrics' ) #打开文件 first_line = f.readline() print ( 'first line:' ,first_line) #读一行 print ( '我是分隔线' .center( 50 , '-' )) data = f.read() # 读取剩下的所有内容,文件大时不要用 print (data) #打印文件 f.close() #关闭文件 |
打开文件的模式有:
- r,只读模式(默认)。
- w,只写模式。【不可读;不存在则创建;存在则删除内容;】
- a,追加模式。【可读; 不存在则创建;存在则只追加内容;】
"+" 表示可以同时读写某个文件
- r+,可读写文件。【可读;可写;可追加】
- w+,写读
- a+,同a
"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)
- rU
- r+U
"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)
- rb
- wb
- ab
其它语法

def close(self): # real signature unknown; restored from __doc__
"""
Close the file. A closed file cannot be used for further I/O operations. close() may be
called more than once without error.
"""
pass def fileno(self, *args, **kwargs): # real signature unknown
""" Return the underlying file descriptor (an integer). """
pass def isatty(self, *args, **kwargs): # real signature unknown
""" True if the file is connected to a TTY device. """
pass def read(self, size=-1): # known case of _io.FileIO.read
"""
注意,不一定能全读回来
Read at most size bytes, returned as bytes. Only makes one system call, so less data may be returned than requested.
In non-blocking mode, returns None if no data is available.
Return an empty bytes object at EOF.
"""
return "" def readable(self, *args, **kwargs): # real signature unknown
""" True if file was opened in a read mode. """
pass def readall(self, *args, **kwargs): # real signature unknown
"""
Read all data from the file, returned as bytes. In non-blocking mode, returns as much as is immediately available,
or None if no data is available. Return an empty bytes object at EOF.
"""
pass def readinto(self): # real signature unknown; restored from __doc__
""" Same as RawIOBase.readinto(). """
pass #不要用,没人知道它是干嘛用的 def seek(self, *args, **kwargs): # real signature unknown
"""
Move to new file position and return the file position. Argument offset is a byte count. Optional argument whence defaults to
SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values
are SEEK_CUR or 1 (move relative to current position, positive or negative),
and SEEK_END or 2 (move relative to end of file, usually negative, although
many platforms allow seeking beyond the end of a file). Note that not all file objects are seekable.
"""
pass def seekable(self, *args, **kwargs): # real signature unknown
""" True if file supports random-access. """
pass def tell(self, *args, **kwargs): # real signature unknown
"""
Current file position. Can raise OSError for non seekable files.
"""
pass def truncate(self, *args, **kwargs): # real signature unknown
"""
Truncate the file to at most size bytes and return the truncated size. Size defaults to the current file position, as returned by tell().
The current file position is changed to the value of size.
"""
pass def writable(self, *args, **kwargs): # real signature unknown
""" True if file was opened in a write mode. """
pass def write(self, *args, **kwargs): # real signature unknown
"""
Write bytes b to file, return number written. Only makes one system call, so not all of the data may be written.
The number of bytes actually written is returned. In non-blocking mode,
returns None if the write would block.
"""
pass

with语句
为了避免打开文件后忘记关闭,可以通过管理上下文,即:
1
2
3
|
with open ( 'log' , 'r' ) as f: ... |
如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。
在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:
1
2
|
with open ( 'log1' ) as obj1, open ( 'log2' ) as obj2: pass
|
程序练习
程序1: 实现简单的shell sed替换功能
程序2:修改haproxy配置文件
需求:
4、字符编码与转码
详细文章:
http://www.cnblogs.com/yuanchenqi/articles/5956943.html
http://www.diveintopython3.net/strings.html
需知:
1.在python2默认编码是ASCII, python3里默认是utf-8
2.unicode 分为 utf-32(占4个字节),utf-16(占两个字节),utf-8(占1-4个字节), so utf-8就是unicode
3.在py3中encode,在转码的同时还会把string 变成bytes类型,decode在解码的同时还会把bytes变回string
python 自动化之路 day 03的更多相关文章
- python 自动化之路 day 04
内容目录: 1. 函数基本语法及特性 2. 参数与局部变量 3. 返回值 4.嵌套函数 5.递归 6.匿名函数 7.函数式编程介绍 8.高阶函数 9.内置函数 1.函数基本语法及特性 背景提要 现在老 ...
- python 自动化之路 day 05
内容目录: 列表生成式.迭代器&生成器 装饰器 软件目录结构规范 模块初始 常用模块 1.列表生成式,迭代器&生成器 列表生成式 需求:列表[0, 1, 2, 3, 4, 5, 6, ...
- python 自动化之路 day 09 进程、线程、协程篇
本节内容 操作系统发展史介绍 进程.与线程区别 python GIL全局解释器锁 线程 语法 join 线程锁之Lock\Rlock\信号量 将线程变为守护进程 Event事件 queue队列 生产者 ...
- python 自动化之路 day 08 面向对象进阶
面向对象高级语法部分 经典类vs新式类 静态方法.类方法.属性方法 类的特殊方法 反射 异常处理 面向对象高级语法部分 经典类vs新式类 把下面代码用python2 和python3都执行一下 1 2 ...
- python 自动化之路 logging日志模块
logging 日志模块 http://python.usyiyi.cn/python_278/library/logging.html 中文官方http://blog.csdn.net/zyz511 ...
- python 自动化之路 day 06
ATM作业讲解: 数据访问层 业务逻辑层 time & datetime模块 import time # print(time.clock()) #返回处理器时间,3.3开始已废弃 , 改成了 ...
- PYTHON 自动化之路 (二)
一.python 模块的使用 模块的使用: import os #调用 os 模块 cmd_s = os.popen("dir").read() #打开路径为结果保存为cmd_sp ...
- python 自动化之路 day 00 目录
目录 初识Python Python基本数据类型 Python基础之函数 Python基础之杂货铺 模块 面向对象 网络编程 HTML CSS JavaScript DOM jQuery Web框架本 ...
- python 自动化之路 day 10 协程、异步IO、队列、缓存
本节内容 Gevent协程 Select\Poll\Epoll异步IO与事件驱动 RabbitMQ队列 Redis\Memcached缓存 Paramiko SSH Twsited网络框架 引子 到目 ...
随机推荐
- pes and ts stream, how to convert
http://stackoverflow.com/questions/4145575/transport-stream-mpeg-file-fromat What you are probably w ...
- Block介绍(一)基础
一.概述 Block是C级别的语法和运行时特性.Block比较类似C函数,但是Block比之C函数,其灵活性体现在栈内存.堆内存的引用,我们甚至可以将一个Block作为参数传给其他的函数或者Block ...
- css3水平翻转
@keyframes cardFront { 0%, 40%, 100% { 02 opacity:1; 03 -webkit-transform:rotateY(0deg); 04 ...
- [USACO10MAR]伟大的奶牛聚集
[USACO10MAR]伟大的奶牛聚集 Bessie正在计划一年一度的奶牛大集会,来自全国各地的奶牛将来参加这一次集会.当然,她会选择最方便的地点来举办这次集会. 每个奶牛居住在 N(1<=N& ...
- SVN版本控制安装配置说明
版本控制好工具有SVN.CVS.VSS等多种,他们的优劣在此不说明,请网络参阅. SVN支持多种平台,此文仅描述Windows平台下使用说明. SVN客户包含客户端和服务端.Windows平台下客户端 ...
- FireMonkey 使用Webbrowser
DELPHI XE5 源码PASCAL:http://files.cnblogs.com/xe2011/FireMonkey_Webbrowser.rar 为了这个用上webbrowser真是费太大劲 ...
- android studio常用快捷键(不断补充)
1.查找类 ctrl + n 2.查找全局文件 双击shift 3.返回上一次编辑的地方 ctrl + shift + backspace 4.代码格式化ctrl + alt + L 5.查看类的结 ...
- [Javascript] Use Number() to convert to Number if possilbe
Use map() and Number() to convert to number if possilbe or NaN. var str = ["1","1.23& ...
- Android Studio中Gradle使用详解
一)基本配置 build配置 buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools. ...
- android优化(json工具,message新建/传递,avtivity深入学习视频)
1,在线json校验工具:www.bejson.com 2, 在handler中经常使用的 message的传递上,message.what使用静态量 . private static final i ...