Python第四课-深入文件与异常(数据持久化)
Python第三课——初探文件与异常 学习的主要是从文件读取数据、异常处理基本语法
本节课学习如何使用Python向文本文件中写入数据、异常处理的深入补充
1、创建文件,并将需要持久化得数据写入文件中。
'''将上课demo中的谈话内容(conversations)按角色(role)的不同,分别存入两个文本文件中'''man = [] #分别定义两个list 用来存储两个role的conversationsother = []try: data = open('sketch.txt') try: for each_line in data: (role, line_spoken) = each_line.split(':', 1) line_spoken = line_spoken.strip() if role == 'man': #通过判断role来确定要存入的list man.append(line_spoken) else: other.append(line_spoken) except ValueError: pass data.close() #别忘了完成文件操作关闭数据文件对象except IOError: print('The file is missing!')try: man_file = open('man_data.txt', 'w') #数据文件对象中的文件参数如果不存在,并且相应目录有相应权限,open()会自动创建文件 other_file = open('other_data.txt', 'w') # 'w'为文件数据对象的'写'模式 print(man, file = man_file) #print()函数中的file参数为写入的文件名 print(other, file = other_file) man_file.close() #别忘了完成文件操作关闭数据文件对象 other_file.close()except IOError: print('File Error!')
man = [] other = []try: data = open('sketch.txt') try: for each_line in data: (role, line_spoken) = each_line.split(':', 1) line_spoken = line_spoken.strip() if role == 'man': man.append(line_spoken) else: other.append(line_spoken) except ValueError: pass data.close()except IOError as ioerr: #将IOError异常对象赋予ioerr变量 print('File Error :' + str(ioerr)) #将ioerr转换为字符串类型try: man_file = open('man_data.txt', 'w') other_file = open('other_data.txt', 'w') print(man, file = man_file) print(other, file = other_file)except IOError as ioerr: print('File Error: ' + str(ioerr))finally: #无论try代码块或者except代码块中的语句是否被执行,finally代码块中的语句 if 'man_file' in locals(): #判断数据文件对象是否存在,loclas() BIF返回作用域中所有变量的字典 man_file.close() if 'man_file' in locals(): man_file.close()
try: with open('man_data.txt', 'w') as man_file: print(man, file = man_file) with open('other_data.txt', 'w') as other_file: print(other, file = other_file)except IOError as ioerr: print('File Error: ' + str(ioerr))
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 ioerr: print('File Error: ' + str(ioerr))