Python读写文件Demo
下面的程序,使用了with关键字,避免冗长的try … catch … finally的写法
# -*- coding: utf-8 -*-
def read_file(file):
with open(file, 'r') as f:
print(f.read()) # 输出语句
f.close()
def write_file(file):
with open(file, 'a') as f:
for i in range(10):
f.write(str(i) + '\n')
f.close()
file = 'test.txt'
write_file(file)
read_file(file)
程序很简单,一个读文件函数,一个写文件函数,运行效果如下: