文件存储与异常
1、打开关闭文件
import os
if os.path.exists('sketch.txt'):
the_file = open('sketch.txt')
print(the_file.readline(),end=' '
the_file.close()
else:
print('the data is missing')
2、split函数
for each_line in data:
if not each_line.find(':') == -1
(role,line_spoken) = each_line.split(':',1) #分成两部分
3、异常处理
try:
the_file = open('sketch.txt')
print(the_file.readline(),end=' '
except IOError:
print('the data is missing')
finally:
the_file.close()
try:
with open ('it.txt',"w") as data:
print("aag",file = data)
except IOError as err:
print("File error:" + str(err) )
4、strip函数
(role,line_spoken) = each_line.split(':',1)
line_spoken = line_spoken.srep() #从字符串去除不想要的字符
5、写入文件
out = open("data.out",'w')
print("NOR iii",file = out)
out.close()
6、保存文件
import pickle
with open('mydata.pickle','wb') as msd
pickle.dump([1,2,'t'],msd)
with open('mydata.pickle','rb') as mrd
mlist = pickle.load(mrd)
print(mlist)