打开文件时,若发生异常,将导致文件不能关闭,使用with语句处理文件时,无论是否抛出异常,都能保证with语句执行完毕后关闭已经打开的文件
with open('a.txt', 'a') as file1:
file1.write('\n这里是使用with语句进行追加文件内容')
pass #空语句
#读出使用with语句后的文件内容
file1 = open('a.txt', 'r')
print(file1.read())
file1.close()
file1 = open('a.txt', 'a')
file1.write('\nhahhah')
file1.flush() #刷新缓冲区,把缓冲区内容写入文件,能保证数据写入磁盘
file1.close()