Python第三课-初探文件与异常
本次代码中用到的'sketch.txt'文件在Head First Python官网上有的下。
从文件读取数据:
常用方式:使用open() BIF和for循环读取基于行的文件内容。
open()使用的基本流程:
data = open(filename): #打开print(data.read()) #处理data.close() #关闭
'''打开一个名为'sketch.txt'的文件.把读取到得每行数据利用':'分割处理为讲话者和讲话内容后输出'''import osif os.path.exists('sketch.txt'): #判断文件是否存在 data = open('sketch.txt') #打开文件 for each_line in data: #按行读取文件 if each_line.find(':') != -1: #判断是否具备分割条件 (role, line_spoken) = each_line.split(':', 1) #分割行 print(role + ' said: ' + line_spoken) #分割后输出 data.close() #关闭文件else: print('The file is missing')s = '2.33'help(s.split)import oshelp(os.path.exists)help(open)
try: #尝试执行的代码except: #用于恢复错误的代码
try: data = open('sketch.txt') for each_line in data: try: (role, line_spoken) = each_line.split(':', 1) print(role + ' said: ' + line_spoken) except ValueError: #处理try代码块内特定错误类型的异常 pass data.close() #关闭文件except: #处理try代码块内所有错误类型的异常 print('The file is missing')