文件的写入
myfile = open('hello.txt','w')
myfile.write('Hello world\n')
Out[4]: 12
myfile.write('Python\n')
Out[5]: 7
myfile.close()
myfile = open('hello.txt','w',encoding = 'utf8') #写入中文默认为GBK编码,改为utf-8编码
文件的读取
f = open('hello.txt','r') #'r'可省略
f.read()
Out[8]: 'Hello world\nPython\n'
f.read()
Out[9]: ''
f = open('hello.txt')
f.readline() #相当于指针,自动读下一行
Out[11]: 'Hello world\n'
f.readline()
Out[12]: 'Python\n'
f.readline()
Out[13]: ''
l = open('hello.txt').readlines() #读取所有行并保存到列表
l
Out[15]: ['Hello world\n', 'Python\n']
for line in l:
...: print(line)
...:
Hello world
Python
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()
Out[39]: b'\x80\x03}q\x00(X\x01\x00\x00\x00aq\x01K\x01X\x01\x00\x00\x00bq\x02K\x02u.'
f = open('datafile.pkl','rb')
data = pickle.load(f)
data
Out[42]: {'a': 1, 'b': 2}
使用with自动关闭文件
with open('hello.txt') as f:
...: for line in f.readlines():
...: print(line)
...:
Hello world
Python
Python自带上下文管理器,执行完with包裹的语句体后会自动关闭文件