python学习三(数据保存到文件)
以写模式打开文件:需要指定写模式,如下所示
data = open('data.out','w')
如果文件已经存在,则会清空它现有的所有内容。要追加一个文件,需要使用访问模式a,会追加到下一行。
例子:将上节中Man和Other Man说的话,分别保存到两个文件中
man = []
other = []
try:
data = open('sketch.txt')
for each_line in data:
try:
(role, line_spoken) = each_line.split(':')
line_spoken = line_spoken.strip()
if role == 'Man':
man.append(line_spoken)
elif role == 'Other Man':
other.append(line_spoken)
else:
pass
except ValueError:
pass
data.close()
except IOError:
print('The datafile is missing!')
#使用print将列表中的数据输出到文件中
try:
with open('man_data.txt', 'w') as man_file, open('other_data.txt', 'w') as other_file:
print(man, file=man_file)
print(other, file=other_file)
except IOError as err:
print('File error: ' + str(err))
使用with open()方法保存文件,不需要再用close方法关闭文件
Python提供了一个标准库,名为pickle,它可以加载、保存几乎任何的Python数据对象,包括列表
使用python的dump保存,load恢复
import pickle
man = []
other = []
try:
data = open('sketch.txt')
for each_line in data:
try:
(role, line_spoken) = each_line.split(':')
line_spoken = line_spoken.strip()
if role == 'Man':
man.append(line_spoken)
elif role == 'Other Man':
other.append(line_spoken)
else:
pass
except ValueError:
pass
data.close()
except IOError:
print('The datafile is missing!')
try:
with open('man_data.txt', 'wb') as man_file, open('other_data.txt', 'wb') as other_file:
pickle.dump(man, file=man_file)
pickle.dump(other, file=other_file)
except IOError as err:
print('File error: ' + str(err))
except pickle.PickleError as perr:
print('Pickling error: ' + str(perr))
'wb'中的b表示以二进制模式打开文件
要读取二进制文件使用'rb'
import pickle
with open('man_data.txt','rb') as readText:
a_list = pickle.load(readText)
print(a_list)