方法一:典型的C编程思维读取文件中的每一行
#读取文件
f = open('a.txt','r')
line = f.readline()
while line:
print(line)
line = f.readline()
输出:
1, first line
2, second line
3, third line
4, fourth line
方法二:没有跟上时代的思维
#读取文件
f = open('a.txt','r')
for line in f.readlines():
print(line)
输出:
1, first line
2, second line
3, third line
4, fourth line
方法三:简洁高效的方法,代码如下:
#读取文件
f = open('a.txt','r')
for line in f:
print(line)
输出:
1, first line
2, second line
3, third line
4, fourth line
需要用到 pickle 模块
pickle.dump(x,f) #把对象x序列化后保存到文件f中
pickle.load(f) #从文件f中还原对象x
举例如下:
import pickle
afile = open('a.txt', 'wb+')#注意模式必须二进制
alist = ['aaa', 'bbb','ccc']
print(alist)
输出:
['aaa', 'bbb', 'ccc']
把对象序列化后保存到文件
pickle.dump(alist,afile)
afile.close()
从文件中还原对象
bfile = open('a.txt','rb')#注意模式必须为二进制
blist = pickle.load(bfile)
bfile.close()
print(blist)
输出:
['aaa', 'bbb', 'ccc']
import pickle
help(pickle) #查看pickle帮助文档