将基于内存的数据存储到磁盘上,这正是持久存储的含义。
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()