文件与类型汇总
1. 基本语法:file = open('文件名',mode)
写文件:myfile=open('hello.txt','w')
myfile.write('优品课堂\n')
myfile.close()
读取文件:f=open('hello.txt','r')('r'可省略)
f.read() --读取所有内容
read相当于指针
重新打开: f = open('hello.txt')
f.readline()
f.readline()
放入列表:
l = open ('hello.txt').readlines() (类型为列表)
for line in l
print(line)
为了防止乱码可指定编码:
f = open ('course.txt','w',encoding='utf8')
读取二进制文件:rb
2. mode: r(读) w(写)a(追加) b(二进制文件)+(读+写)
3.类型的丢失
x,y,z=1,2,3
l=[1,2,3]
f=open('datafile.txt','w')
f.write('{},{},{}'.format(x,y,z))
f.write(str(l))
f.close()
chars = open('datafile.txt').read()
序列化--pickle存取python对象:
d ={'a':1,'b':2}
f = open('datafile.pkl','wb')
import pickle
pickle.dump(d,f)
f.close()
不要用记事本打开
open('datafile.pkl','rb').read() (读取无意义)
f = open ('datafile.pkl','rb')
data=pickle.load(f)
data['a']
data.get('b')
防止忘记关闭文件的做法:
传统方法:
f=open('course.txt')
l=f.readlines()
for line in l
print(line)
close()
新方法
with open('course.txt') as f
for line in f.readlines()
print(line)
数据类型汇总:
集合
1.序列 可变(列表list)/不可变(字符串string,元组tuple,字节数组)
2.映射 字典表dict
3.集合 set:集合信息不能有重复,花括号,但没有键
数字
1.整型 int/boolean
2.浮点型 float/decimal/fraction
可调用
1.函数 function
2.生成器 Generation
3.类 Class
4.方法
其他
1.模块
2.实例
3.文件
4.None
5.视图
内部
1.type
在内存中的表现:
l=['abc',[(1,2),([3],4)],5]