python读取文件,如果未找到,可以抛错处理
def main(): f =open('致橡树.txt','r',encoding='utf-8') print(f.read()) f.close() def test(): f= None try: f = open("致橡树.svb",'r',encoding='utf-8') print(f.read()) except FileNotFoundError: print("无法打开指定文件!") except LookupError: print('指定了未知的编码!') except UnicodeDecodeError: print('读取文件时解析错误!') finally: if f: f.close() if __name__ =="__main__": main() test()
def main(): f =open('致橡树.txt','r',encoding='utf-8') print(f.read()) f.close() def test(): f= None try: f = open("致橡树.svb",'r',encoding='utf-8') print(f.read()) except FileNotFoundError: print("无法打开指定文件!") except LookupError: print('指定了未知的编码!') except UnicodeDecodeError: print('读取文件时解析错误!') finally: if f: f.close() def files(): filenames =('a.txt','b.txt','c.txt') fs_list =[] try: for filename in filenames: fs_list.append(open(filename,'w',encoding='utf-8')) for number in range(1,10000): if number < 100: fs_list[0].write(str(number) + '\n') elif number < 1000: fs_list[1].write(str(number) + '\n') elif number < 10000: fs_list[2].write(str(number) + '\n') except IOError as ex: print(ex) print('写入文件时发生错误!') finally: for fs in fs_list: fs.close() print('操作成功') if __name__ =="__main__": main() test() files()