Python持久存储--数据保存到文件

将基于内存的数据存储到磁盘上,这正是持久存储的含义。


try:
	data = open('scatch.txt')
	man = []
	woman = []
	for each_line in data:
		try:
			(role,line_spoken) = each_line.split(':',1)		
			line_spoken = line_spoken.strip()
			if role == 'Man':
				man.append(line_spoken)
			elif role == 'Woman':
				woman.append(line_spoken)
		except ValueError:
			pass
	print(man)
	print(woman)
	data.close()
except IOError:
    print("The file is missing!")

运行结果:

['Hi.', 'How are you?', "I'm file,too.", 'Thanks.']
['Hi.', "I'm fine,thank you.And you?", 'Okay.hi:']


==========================================================

Python的open()BIF除了可以打开文件来读文件,当然也可以写文件,不是吗?

使用open()BIF打开磁盘文件时,可以指定使用什么访问模式。默认地,open()使用模式r表示读,所以不需要专门指定r模式,要打开一个文件完成写,需要使用模式w:

out = open("data.out","w")

默认地,print()BIF显示数据时会使用标准输出(通常是屏幕)。要把数据写至一个文件,需要使用file参数来指定所使用的数据文件对象。

print("Today is a good day.",file= out)

完成工作时,一定要关闭文件,确保所有数据都写至磁盘。这称为刷新输出(flushing)。

out.close()


r:读。r+:读写。不创建。覆盖写。

w:写。w+:读写。创建。覆盖写。

a:写。a+: 读写。创建。附加写。

out.seek(0)

out.read()

解决方案:读取之前将指针重置为文件头。

try:
	data = open('scatch.txt')
	man = []
	woman = []
	for each_line in data:
		try:
			(role,line_spoken) = each_line.split(':',1)	
			line_spoken = line_spoken.strip()
			if role == 'Man':
				man.append(line_spoken)
			elif role == 'Woman':
				woman.append(line_spoken)
		except ValueError:
			pass
	data.close()
except IOError:
    print("The file is missing!")
try:
        out_man = open("man_data.txt","w+")
	out_woman = open("woman_data.txt","a+")
	print(man,file=out_man)
	print(woman,file = out_woman)
        out_man.seek(0)
	out_woman.seek(0)
	out_man.read()
	out_woman.read()
	out_man.close()
	out_woman.close()
except IOError:
        print("File error")  
改进后:

try:
        out_man = open("man_data.txt","w+")
	out_woman = open("woman_data.txt","a+")
	print(man,file=out_man)
	print(woman,file = out_woman)
        out_man.seek(0)
	out_woman.seek(0)
	out_man.read()
	out_woman.read()
except IOError:
        print("File error")
finally:
        out_man.close()
	out_woman.close()

不论什么情况,finally块儿总会执行。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值