6.2.6 读写文件
每个Path实例都包含一些方法来处理所指示文件的内容。要直接获取内容,可以使用read_bytes()或read_text()。要写入文件,可以使用write_bytes()或write_text()可以使用open()方法打开文件并保留文件句柄,而不是向内置的open()函数传入文件名。
import pathlib
f = pathlib.Path('example.txt')
f.write_bytes('This is the content'.encode('utf-8'))
with f.open('r',encoding='utf-8') as handle:
print('read from open():{!r}'.format(handle.read()))
print('read_text():{!r}'.format(f.read_text('utf-8')))
这些便利方法会在打开文件和写入文件之前完成一些类型检查,除此之外,它们与直接操作是等价的。
运行结果:
read from open():‘This is the content’
read_text():‘This is the content’