python支持的数据类型
int | 整数型 |
float | 浮点型 |
complex | 复数,实数+虚数,虚数部分以“j”或“J”结尾,a+bj或者complex(a,b) |
字符串 | python不支持字符类型,所有字符都以字符串的形式存在,'a'或者"abc" |
布尔类型 | True和False,运算and(与)、or(或)、not(非)。False以0、0.0、空字符串‘’或“”、None、空集合,包括空元组()、空序列[]、空字典{}。其他的都是True |
None | 空值,不支持任何运算,也没有任何内置函数方法。和其他数据类型相比永远返回False。未指定返回值的函数会自动返回None |
变量(variable)命名规则:
- 以_、数字、字母组成,不能是特殊符,包括空格也不行。
- 不能以数字开头,保留字符(命令字符)不能使用,不能以中文为变量名(python 3.x支持,但没有公司允许)。
- 不能以大写开头,变量名首个单词小写,后面的单词可首字母大写(注:变量对应的常量,例如pie=3.151592653……,python不区分常量和变量,程序员为了区分常量和变量,python中常量和变量,所以常量用全部大写的变量名来定义常量)。
单行注释用#,多行注释用3个'或者3个"括起来
字符串和字节
python2中用str表示字节字符串,默认保存ASII码。这种类型在Python3中用bytes对象来处理,明确区分字符串与字节。python3中只有一种能够保存文本信息的数据类型,就是str,它是不可变序列,保存的是Unicode码位
在python2中,Unicode需要有前缀(例如u"some string")。从python3.3开始,为保证向后兼容,仍然支持这个前缀,但它在python3中没有任何语法上的意义。字节的明确语法:字节也被单引号,双引号或三引号包围,但必须有一个b或B前缀。
字符串常用方法
python里创建一个字符串可用单引号' '或者双引号" " 特性:不可修改
s = 'a' str = "my name is luxi and I am 20"
1.输出字符串:
# 逐个输出字符串str str = "abcdefg" for i in range(0,len(str)): print(str[i]) a b c d e f g
range()函数原型:range(start, end, scan):
参数含义:
start:计数从start开始。默认是从0开始。例如range(3)等价于range(0, 3);
end:计数到end结束,但不包括end.例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5
scan:每次跳跃的间距,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1)
name = "my name is luxi and I am 20" print(name) name1 = "my name is %s and I am %d" print(name1 % ("luxi",20)) name2 = "my name is {name} and I am {age}" print(name2.format(name="luxi",age=20)) name3 = "my name is {0} and I am {1}" print(name3.format("luxi",20)) # 这四种方式输出的结果都是 my name is luxi and I am 20
%s 字符串,%d 整数,%f 浮点数
format()是python2.6新增的一个格式化字符串的方法,功能非常强大,有可能在未来完全替代%格式化方法,相比 % ,format()的优点有:
1.格式化时不必关心数据类型的问题,format()会自动转换
2. 单个参数可以多次输出,参数顺序可以不同
3. 填充方式灵活,对齐方式强大
2.字符串常用方法
s = 'a' str = "my name is luxi and I am 20"
str.capitalize() # 首字母大写 My name is luxi and i am 20
str.count('a') # 统计 a 的个数,应该就是3个了 3
str.center(50, "-") # 字符串居中,一共打印50个字符,不够"-"来凑 ------------my name is luxi and I am 20-----------
str.endswith("wll") # 判断字符串是不是以"wll"结尾,返回真假 False
str = "my \tname is luxi and I am 20" str.expandtabs(tabsize=30) # 在\t处打印30个空格,Python expandtabs() 方法把字符串中的 tab 符号('\t')转为空格,tab 符号('\t')默认的空格数是 8。
my name is luxi and I am 20
str.find("y") # 索引,找到第一个y的位置,从0开始 1
# str.find()方法只能找到第一个位置,如果要找所有的 str = "my name is luxi and I am 20" print(str.find('m')) print("---------------------") count = 0 for i in range(len(str)): if 'm' == str[i]: count = count + 1 print("m在第",i,"个") print("m的总个数为", count) 0 --------------------- m在第 0 个 m在第 5 个 m在第 23 个 m的总个数为 3
str[str.find("name"):] # 切片,从"name"开始一直到最后打印,切片在列表会说到 name is luxi and I am 20
str = "my name is {name} and I am {age} years old" str.format(name='luxi', age=20) my name is luxi and I am 20 years old str.format_map({'name': 'luxi', 'age': 22}) # .format的字典用法 my name is luxi and I am 20 years old
str.isalnum() # 判断是不是阿拉伯数字(英文字符+1~9),特殊字符不行,这里有空格 False 'abc123'.isalnum() # abc123只有英文字符abc和123,这就可以 True
str.isalpha() # 判断是不是纯英文字符,显然不是 False 'abA'.isalpha() # 这就是了 True
'a1'.isidentifier() # 判断是不是一个合法的标识符(变量名),什么是合法的标识符,由字母和数字、下划线组成,开头不能是数字 True
str.islower()#判断是不是小写 False str.isupper() # 有小写就有大写,判断是不是大写 False
str.isnumeric() # 判断是不是数字(只有数字,有小数点不行) False
str.istitle() # 判断每个首字母是不是大写 False 'My Name'.istitle() # 这显然就是了嘛 True
' '.isspace()) # 判断是不是空格 True
'+'.join(['1', '2', '3'])#连成字符串 1+2+3
str.ljust(50, '*') # 一共打印50个字符,不够*来凑(在右边) my name is luxi and I am 20*********************** name.rjust(50, '*') # 有在右边的就有在左边的,一共打印50个字符,不够*来凑(在左边) ***********************my name is luxi and I am 20
str.lower() # 把字符串大写改成小写 my name is luxi and i am 20 str.upper() # 把字符串小写改成大写 MY NAME IS LUXI AND I AM 20
str.replace('a', 'A') # 替换,把a换成A my nAme is luxi And I Am 20 str.replace('a', 'A', 1) # 替换,把a换成A,后面有个1,意思只换一个 my nAme is luxi and I am 20
str.rfind('a') # 找到最右边的a的下标 22
name.split() # 把字符串按空格分成列表 ['my', 'name', 'is', 'luxi', 'and', 'I', 'am', '20']
'1+2+3+4'.split('+') # 把字符串按+分成列表 ['1', '2', '3', '4']
'1+2\n+3+4'.splitlines() # 把字符串按换行分成列表 ['1+2', '+3+4']
str.swapcase() # 把字符串小写变大写,大写变小写 MY NAME IS LUXI AND i AM 20
str.title() # 把字符串每个首字母变大写 My Name Is Luxi And I Am 20
str.zfill(50) # 打印50个字符,不够用0填充 00000000000000000000000my name is luxi and I am 20
补充一个小点,和字符串无关,三元组:三元运算,如果条件(a > b)为真则 d 值为a,否则 d 值为c
a = 1 b = 2 c = 3 d = a if a > b else c print(d) 3
元组
元组是有序的,只有index和count两种方法,切记元组不可更改
names = ('张三', '李四', '王五', '赵六', '许二', '李四')
print(names.index('张三')) # 找'张三'在元组中的第几个,从0开始 0
print(names.count('李四')) # 计数,'李四'在元组中有几个 2
print(names) # 输出元组 print(names[0]) # 输出元组的第一个元组,下标从0开始 ('张三', '李四', '王五', '赵六', '许二', '李四') 张三
# 逐个输出元组中的每个元素 for i in names: print(i) print("------------------") for i in range(len(names)): print(names[i]) 张三 李四 王五 赵六 许二 李四 ------------------ 张三 李四 王五 赵六 许二 李四
列表
列表也是有序的。
names = ['张三', '李四', '王五', '赵六', '许二', '李四']
names.append("WR") # 插在最后一个 print(names) names.insert(1, "YT") # 插在第二个的位置上 print(names) ['张三', '李四', '王五', '赵六', '许二', '李四', 'WR'] ['张三', 'YT', '李四', '王五', '赵六', '许二', '李四', 'WR']
1.del根据索引删除列表元素del list[1];2.remove()方法直接删除列表里的元素list.remove('张三')或者list.remove(2019);3.pop()方法删除列表指定位置的元素,无参数时删除最后一个元素list.pop(2)或者list.pop()
names.remove("李四") # 如果有多个,只删除一个 print(names) del names[2] # 删除列表中第三个元素,下标是2,从零开始 print(names) names.pop() # 默认不输入下标,则删除最后一个值 print(names) ['张三', '王五', '赵六', '许二', '李四'] ['张三', '王五', '许二', '李四'] ['张三', '王五', '许二']
names[2] = "Jxx" # 把第三个元素改为‘Jiangxiaoxia’ print(names) ['张三', '李四', 'Jxx', '赵六', '许二', '李四']
print(names) print(names[0]) # 切片,输出第一个元素 print(names[1:3]) # 切片,左闭右开,输出从第二个到第三个 print(names[3]) # 切片,输出第四个元素 print(names[-1]) # 切片,-1表示最后一个元素 print(names[-3:-1]) # 切片,从左往右数,不能从右往左数 print(names[-3:]) # 切片,数到最后一个,冒号后面忽略 print(names[:3]) # 切片,第一个开始数,冒号前面可以忽略,相当于[0:3] print(names[0:-1:2]) # 切片,从0开始到最后一个,步长为2 print(names[::2]) # 切片,从0开始到最后一个,步长为2 print(names[:]) # 切片,从0开始到最后一个,默认步长为1 #输出 ['张三', '李四', '王五', '赵六', '许二', '李四'] 张三 ['李四', '王五'] 赵六 李四 ['赵六', '许二'] ['赵六', '许二', '李四'] ['张三', '李四', '王五'] ['张三', '王五', '许二'] ['张三', '王五', '许二'] ['张三', '李四', '王五', '赵六', '许二', '李四']
其他方法
print(names.index("王五")) # 索引,获取下标 print(names[names.index("许二")]) # 许二是4,输出列表里4的元素,还是许二 2 许二
print(names.count("李四")) # #计数,列表里李四的个数 2
names.clear() # 清除 print(names) []
names.reverse() # 反转 print(names) # 输出 ['李四', '许二', '赵六', '王五', '李四', '张三']
names.sort() # 排序,按照ASCII码排序 print(names) # 输出 ['张三', '李四', '李四', '王五', '许二', '赵六']
names2 = [1, 2, 3, 4] names.extend(names2) # 合并 print(names) # 输出 ['张三', '李四', '王五', '赵六', '许二', '李四', 1, 2, 3, 4]
# 循环输出列表 for i in names: print(i) #输出 张三 李四 王五 赵六 许二 李四
import copy names = ["张三", "李四", ["三子", "王五"], "赵六", "许二", "李四"] names2 = copy.deepcopy(names) # 深copy,指向同一块地址 print(names) print(names2) names[3] = "沈阳" names[2][0] = "Ran" print(names) #输出 ['张三', '李四', ['三子', '王五'], '赵六', '许二', '李四'] ['张三', '李四', ['三子', '王五'], '赵六', '许二', '李四'] ['张三', '李四', ['Ran', '王五'], '沈阳', '许二', '李四']
字典
字典 key-value
字典的特性:
- dict是无序的
- key必须是唯一的,so 天生去重
info = {"29": "张三", "18": "李四", "27": "王五", "16": "赵六"}
1.输出字典里的元素
for i in info: # 建议用这种 print(i, info[i]) print("-"*20) for k, v in info.items(): # 不建议用这种,数据量大的话很崩溃 print(k, v) #输出 29 张三 18 李四 27 王五 16 赵六 --------------------
29 张三
18 李四
27 王五
16 赵六
print(sorted(info.items(), key=lambda d: d[0], reverse=True)) # 根据key的值倒序输出字典里的元素 #输出 [('29', '张三'), ('27', '王五'), ('18', '李四'), ('16', '赵六')]
print(info.items()) # 把字典转成列表 info_3 = dict.fromkeys([1, 2, 3], [1, {"name": "wll"}, 111]) # 也是一种创建字典 print(info_3) info_3[2][1]["name"] = "bbb" # 你以为只改了一个,其实都改了 print(info_3) #输出 dict_items([('29', '张三'), ('18', '李四'), ('27', '王五'), ('16', '赵六')]) {1: [1, {'name': 'wll'}, 111], 2: [1, {'name': 'wll'}, 111], 3: [1, {'name': 'wll'}, 111]} {1: [1, {'name': 'bbb'}, 111], 2: [1, {'name': 'bbb'}, 111], 3: [1, {'name': 'bbb'}, 111]}
2.改
info_2 = {"01": "新鑫", "02": "文文"} info["29"] = "许二" print(info) info.update(info_2) # 有的更新,没有的创建 print(info) #输出 {'29': '许二', '18': '李四', '27': '王五', '16': '赵六'} {'29': '许二', '18': '李四', '27': '王五', '16': '赵六', '01': '新鑫', '02': '文文'}
3.增
info["20"] = "王宇" print(info) #输出 {'29': '张三', '18': '李四', '27': '王五', '16': '赵六', '20': '王宇'}
4.删
info.pop("29") # 标准删 print(info) del info["18"] print(info) info.popitem() # 随机删 print(info) #输出 {'18': '李四', '27': '王五', '16': '赵六'} {'27': '王五', '16': '赵六'} {'16': '赵六'}
5.查
print(info["29"]) # 不建议用这种方法,除非很确定字典里有这个键值 print(info.get("29")) # 一般用这种方法 print("29" in info) # info.has_key("29") #输出 张三 张三 True
6.多层嵌套
1 list_move = {"电影": { 2 "美国": ["恐怖游轮", "记忆碎片", "穆赫兰道"], 3 "中国": ["唐人街探案", "杀破狼", "使徒行者"] 4 }, "电视剧": { 5 "美国": ["城堡岩", "神探夏洛克", "假面真情"], 6 "中国": ["暗黑者", "武林外传", "无证之罪"] 7 }, "动漫": { 8 "日本": ["名侦探柯南", "进击的巨人", "灌篮高手"], 9 "中国": ["画江湖系列", "狐妖小红娘", "全职高手"] 10 } 11 } 12 list_move["动漫"]["中国"][1] = "斗破苍穹" 13 print(list_move) 14 15 list_move.setdefault("小说", {"中国": [1,2]}) # 在字典里找"小说",如果能取到,返回,如果取不到,就创建一个新的key,value值为逗号后面的 16 print(list_move) 17 18 #输出 19 {'电影': {'美国': ['恐怖游轮', '记忆碎片', '穆赫兰道'], '中国': ['唐人街探案', '杀破狼', '使徒行者']}, '电视剧': {'美国': ['城堡岩', '神探夏洛克', '假面真情'], '中国': ['暗黑者', '武林外传', '无证之罪']}, '动漫': {'日本': ['名侦探柯南', '进击的巨人', '灌篮高手'], '中国': ['画江湖系列', '斗破苍穹', '全职高手']}} 20 {'电影': {'美国': ['恐怖游轮', '记忆碎片', '穆赫兰道'], '中国': ['唐人街探案', '杀破狼', '使徒行者']}, '电视剧': {'美国': ['城堡岩', '神探夏洛克', '假面真情'], '中国': ['暗黑者', '武林外传', '无证之罪']}, '动漫': {'日本': ['名侦探柯南', '进击的巨人', '灌篮高手'], '中国': ['画江湖系列', '斗破苍穹', '全职高手']}, '小说': {'中国': [1, 2]}}
7.其他方法
# values 取值 info.values() dict_values(['张三', '李四', '王五', '赵六']) # keys 取键 info.keys() dict_keys(['29', '18', '27', '16']) # setdefault 取出一个已有键的值(直接返回结果),取出一个不存在的键的值(返回默认键的值,并且将新的键值保存在字典中) info.setdefault("26","Alex") # 返回"Alex" info.setdefault("29","许二") # 返回"张三" # update 更新数据,对已有的键更改值,没有的直接添加 b = {1: 2, 3: 4, "18": "许二"} info.update(b) #info{'29': '张三', '18': '许二', '27': '王五', '16': '赵六', 1: 2, 3: 4} # items 以列表返回可遍历的(键, 值) 元组数组 dict_items = info.items() # dict_items([('29', '张三'), ('18', '许二'), ('27', '王五'), ('16', '赵六'), (1, 2), (3, 4)]) # 通过一个列表生成默认dict,有个没办法解释的坑,少用吧这个 dict_items = dict.fromkeys([1,2,3],'testd') # 会全部更改dict_items{1: 'testd', 2: 'testd', 3: 'testd'}
集合
集合是无序的,自动去重
可变集合(set):可添加和删除元素,非可哈希的,不能用作字典的键,也不能做其他集合的元素
不可变集合(frozenset):与上面恰恰相反
只能通过方法set()和frozenset()创建集合
s1 = set('abc') s2= frozenset('bcd')
a = t | s # t 和 s的并集 b = t & s # t 和 s的交集 c = t – s # 求差集(项在t中,但不在s中) d = t ^ s # 对称差集(项在t或s中,但不会同时出现在二者中) 基本操作: t.add('x') # 添加一项 s.update([10,37,42]) # 在s中添加多项 t.remove('H') # 使用remove()可以删除一项: len(s) # set 的长度 x in s # 测试 x 是否是 s 的成员 x not in s #测试 x 是否不是 s 的成员 s.issubset(t) s <= t # 测试是否 s 中的每一个元素都在 t 中 s.issuperset(t) s >= t # 测试是否 t 中的每一个元素都在 s 中 s.union(t) s | t # 返回一个新的 set 包含 s 和 t 中的每一个元素 s.intersection(t) s & t # 返回一个新的 set 包含 s 和 t 中的公共元素 s.difference(t) s - t # 返回一个新的 set 包含 s 中有但是 t 中没有的元素 s.symmetric_difference(t) s ^ t # 返回一个新的 set 包含 s 和 t 中不重复的元素 s.copy() # 返回 set “s”的一个浅复制
list_1 = [1, 1, 2, 3, 4, 5, 6, 8, 2, 5] list_1 = set(list_1) list_2 = set([3, 22, 3, 5, 10, 12]) print(list_1, type(list_1), list_2) # 打印集合1,1的类型,集合2 # 输出 {1, 2, 3, 4, 5, 6, 8} <class 'set'> {3, 5, 10, 12, 22} # list_1的类型是set,集合,集合是自动去重的
print(list_1.intersection(list_2)) # 交集 # 输出 {3, 5}
print(list_1 & list_2) # 交集 # 输出 {3, 5}
print(list_1.union(list_2)) # 并集 # 输出 {1, 2, 3, 4, 5, 6, 8, 10, 12, 22}
print(list_1 | list_2) # 并集 # 输出 {1, 2, 3, 4, 5, 6, 8, 10, 12, 22}
print(list_1.difference(list_2)) # 差集,在1里面不在2里面 print(list_2.difference(list_1)) # 差集,在2里面不在1里面 # 输出 {1, 2, 4, 6, 8} {10, 12, 22}
print(list_1 - list_2) # 差集,在1里不在2里 print(list_2 - list_1) # 差集,在2里不在1里 # 输出 {1, 2, 4, 6, 8} {10, 12, 22}
print(list_1.symmetric_difference(list_2)) # 对称差集,去掉1和2的交集之后再合并 # 输出 {1, 2, 4, 6, 8, 10, 12, 22}
print(list_1 ^ list_2) # 对称差集,去掉1和2的交集之后再并 # 输出 {1, 2, 4, 6, 8, 10, 12, 22}
list_3 = set([1, 2, 3]) print(list_3.issubset(list_1)) # 3是不是1的子集,是则返回True,否则返回False print(list_1.issuperset(list_3)) # 1是不是3的父子集,即3是不是1的子集 # 输出 True True
其他方法
list_3 = set([1, 2, 3]) list_4 = set([4, 5, 6]) print(list_3.isdisjoint(list_4)) # 3和4没有交集返回为True,有交集返回为False # 输出 True
list_1.add(66) # 添加元素 print(list_1) # 输出 {1, 2, 3, 4, 5, 6, 66, 8} # 集合是无序的,随机添加位置
list_1.update([88, 2333]) # 添加多个元素 print(list_1) # 输出 {1, 2, 3, 4, 5, 6, 66, 8, 88, 2333}
list_1.remove(1) # 删除,直接删除元素值 print(list_1) # 输出 {2, 3, 4, 5, 6, 8}
print(len(list_1)) # 长度 # 输出 7
print(1 in list_1) # 1在集合里吗 print(1 not in list_1) # 1不在集合里吗 # 输出 True False
list_5 = list_1.copy() # 浅复制 print(list_5) #输出 {1, 2, 3, 4, 5, 6, 8}
print(list_1.pop(), list_1) # 删除任一一个元素,并且将那个元素返回 # 输出 1 {2, 3, 4, 5, 6, 8}
print(list_1.discard(6666), list_1) # 删除,remove删除不存在的元素会报错,discard只返回None # 输出 None {2, 3, 4, 5, 6, 8}
文件
对文件操作流程
- 打开文件,得到文件句柄并赋值给一个变量
- 通过句柄对文件进行操作
- 关闭文件
1.打开文件
f = open("文件名", '读写打开模式', encoding="编码形式")
打开文件的模式有:
- 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
有open就有close,不管是读文件还是写文件,最后一定要关闭文件,f.close()
2.基本操作
f = open('lyrics') # 打开文件 first_line = f.readline() print('first line:',first_line) # 读一行 print('我是分隔线'.center(50,'-')) data = f.read() # 读取剩下的所有内容,文件大时不要用 print(data) # 打印文件 f.close() # 关闭文件
f = open("helloworld2", 'r', encoding="utf-8") s = f.read().strip() print(s)
f = open("helloworld2", 'r', encoding="utf-8") info = f.readlines() for i in info: print(i.strip()) f.close()
f = open("helloworld2", 'r', encoding="utf-8") for i in range(3): print(f.readline().strip())
f = open("helloworld2", 'r', encoding="utf-8") for index, line in enumerate(f.readlines()): if index == 3: # 第三行上下分割 print("---------------------") continue print(line.strip())
# 高效的循环方法 f = open("helloworld2", 'r', encoding="utf-8") count = 0 for line in f: if count == 3: print("---------------------") count += 1 continue print(line.strip()) count += 1
# 声明:s为字符串,rm为要删除的字符序列
s.strip(rm) 删除s字符串中开头、结尾处,位于 rm删除序列的字符
s.lstrip(rm) 删除s字符串中开头处,位于 rm删除序列的字符
s.rstrip(rm) 删除s字符串中结尾处,位于 rm删除序列的字符
注意:
1. 当rm为空时,默认删除空白符(包括'\n', '\r', '\t', ' ')
2.这里的rm删除序列是只要边(开头或结尾)上的字符在删除序列内,就删除掉。
f = open("helloworld", "r", encoding="utf-8") f_new = open("helloworld1.bak", "w", encoding="utf-8") for line in f: if "wll" in line: line = line.replace("wll", "wulanlan") f_new.write(line) f.close() f_new.close() #helloworld内容 Hello World Python wll ly jiang syq jxx #helloworld1.bak内容 Hello World Python wulanlan #将wll改成了wulanlan ly jiang syq jxx
with语句
为了避免打开文件后忘记关闭,可以通过管理上下文,
with open('log','r') as f: ...
当with代码块执行完毕时,内部会自动关闭并释放文件资源。
在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,
with open('log1') as obj1, open('log2') as obj2: pass
3.其它方法
for line in f: print line :通过迭代器访问。
file.read([size]):size 未指定则返回整个文件,如果文件大小 >2 倍内存则有问题。
def close(self): # 关闭的文件不能用于进一步的I/O操作。close()可以多次调用,没有错误。 def fileno(self, *args, **kwargs): # 返回基础文件描述符(整数) def isatty(self, *args, **kwargs): # 如果文件连接到tty设备,则为true。 def read(self, size=-1): # 通常读取字节大小,以字节形式返回.注意,不一定能全读回来 # 只进行一次系统调用,因此返回的数据可能比请求的少。 # 在非阻塞模式下,如果没有可用数据,则返回“无”。 # 返回EOF处的空字节对象。 return "" def readable(self, *args, **kwargs): # 如果文件以读取模式打开,则为true def readall(self, *args, **kwargs): # 从文件中读取以字节形式返回的所有数据。 # 在非阻塞模式下,返回立即可用的,如果没有可用数据,则为无。 # 返回EOF处的空字节对象。 def readinto(self): # 与RawIOBase.readinto()相同。 # 不要用,没人知道它是干嘛用的 def seek(self, *args, **kwargs): # 移动到新文件位置并返回文件位置。 # 参数偏移量是字节计数。可选参数,默认值为 # eek_set或0(从文件开始的偏移量,偏移量应大于等于0); # seek_cur”或“1”(相对于当前位置移动,正或负) # seek_end或“2”(相对于文件结尾移动,通常为负,尽管许多平台允许在文件结尾以外进行查找)。 # 请注意,并非所有文件对象都是可查找的。 def seekable(self, *args, **kwargs): #如果文件支持随机访问,则为true。 def tell(self, *args, **kwargs): #当前文件位置。无法为不可查找的文件引发OSError。 def truncate(self, *args, **kwargs): # 将文件截断到最大大小字节,并返回截断的大小。 # 大小默认为当前文件位置,由tell()返回。 # 当前文件位置更改为大小值。 def writable(self, *args, **kwargs): # 如果文件以写模式打开,则为true。 def write(self, *args, **kwargs): # 将字节写入文件,返回写入的数字。 # 只进行一次系统调用,因此并非所有数据都可以写入。 # 返回实际写入的字节数。在非阻塞模式下,如果写入将阻塞,则返回“无”。
字符编码和转码
需知:
1.在python2默认编码是ASCII, python3里默认是unicode
2.unicode 分为 utf-32(占4个字节),utf-16(占两个字节),utf-8(占1-4个字节), so utf-16就是现在最常用的unicode版本, 不过在文件里存的还是utf-8,因为utf8省空间
3.在py3中encode,在转码的同时还会把string 变成bytes类型,decode在解码的同时还会把bytes变回string
#-*-coding:gb2312 -*- #这个也可以去掉 __author__ = 'Alex Li' import sys print(sys.getdefaultencoding()) msg = "我爱北京天安门" #msg_gb2312 = msg.decode("utf-8").encode("gb2312") msg_gb2312 = msg.encode("gb2312") #默认就是unicode,不用再decode gb2312_to_unicode = msg_gb2312.decode("gb2312") gb2312_to_utf8 = msg_gb2312.decode("gb2312").encode("utf-8") print(msg) print(msg_gb2312) print(gb2312_to_unicode) print(gb2312_to_utf8)