如果文件不存在,则捕捉异常,进行新建该twst.txt文件并写入一些话,最后关闭文件(并模拟错误)
收起
file1 = 'test.txt' try: f = open(file1, 'r') print(f.read()) f.close() except: print(f'文件{file1}不存在') file2 = 'twst.txt' try: f = open(file2, 'w') f.write('asdfjkl123456') f.close() print('写入成功') except: print(f'文件{file2}不存在,或写入错误')
报告相同问题?