- 文件的输入和输出
- with 打开方式
- 读取文件的常见方式
- 写入文件的常用方式
f = open('foo.txt', 'rt') # Open for reading (text)
g = open('bar.txt', 'wt') # Open for writing (text)
读取数据。
f.read()
写入数据
g.write('some text')
文件关闭
f.close() g.close()with 打开方式
使用with 关闭文件的工具,会默认关闭文件。
with open(filename, 'rt') as file: pass读取文件的常见方式
一次读取整个文件作为字符串。
with open('foo.txt', 'rt') as file:
data = file.read()
通过迭代逐行读取。
with open(filename, 'rt') as file:
for line in file:
pass
写入文件的常用方式
写入字符串数据。
with open('outfile', 'wt') as file:
file.write('Hello Worldn')
...
重定向打印功能。
with open('outfile', 'wt') as file:
print('Hello World', file = file)
...



