print('#创建test文件并写入(‘w’ 模式)')
f = open('test', 'w')
f.write('this is a text file. \nhello word! \npython is good!')
f.close()
print('#打开文件,并读出文件内容')
f = open('test').read()
print(f)
# f.close()
print('#将文件每行内容写进列表')
f = open('test')
lines = f.readlines()
print(lines)
f.close()
print('#在原有文件内容基础上继续添加内容(‘a’ 模式)')
f = open('test', 'a')
f.write('\nwant anymore!')
f.close()
print('#循环打印每行文件内容')
f = open('test')
for test_1 in f:
print(test_1)
f.close()
print('#\'with\'具有自动关闭文件功能')
with open('test') as f:
print(f.read())
print('#删除文件')
import os
os.remove('test')
运行结果如下: