文件操作是学习Python必备的技能, Python同时也是所有编程语言中文件操作最简单的。
- 文件写
f = open('file.txt', 'w')
content = 'this is a program\n'
f.write(content)
f.close()
- 文件追加
f = open('file.txt', 'a')
content = 'this is another program\n'
f.write(content)
f.close()
- 读文件
f = open('file.txt', 'r')
content = f.read()
print(content)
f.close()
this is a program
this is another program
- 另一种表示
with open('file.txt', 'r') as f:
content = f.read()
print(content)
this is a program
this is another program
- 按行读文件
f = open('file.txt', 'r')
lines = f.readlines()
for line in lines:
print(line)
f.close()
this is a program
this is another program