一、open 函数的参数
要读写文件,首先要通过内置函数open打开文件,获的文件对象
open(
file,
mode='r',
buffering=-1,
encoding=None,
errors=None,
newline=None,
colsefd=True,
opener=None
)
常用参数
file 参数指定了要打开文件的路径
mode 参数指定了文件打开的模式,决定了可以在怎么操作文件。
常用的打开模式
r 只读
w 只写
a 追加写入
encoding 参数指定了读写文本文件时,使用的 字符串编码 方式
调用open函数时,如果传入了encoding参数值:
调用write写入字符串到文件中,open函数会使用指定的encoding编码为字符串;
调用read读取文件中的内容,open函数会使用指定的encoding编码为字符串,read函数有参数size,用来指定这次读取多少个字符
示例
# 指定编码方式为 utf8
f = open( test.txt, 'w', encoding='uft8' )
# write 方法会将字符串编码为 utf8 字符串写入文件
f.write('hello world!')
# 文件操作完毕后,使用close方法关闭该文件对象
f.close()
二、with 语句
在进行文件读写之后,忘记使用close方法关闭文件,就可能造成意想不到的问题。
可以使用with语句打开文件,就不需要调用close方法关闭文件。
# open 返回的对象 赋值为 变量 f
with open('test.txt') as f:
linelist = f.rendlines()
for lin in linelist:
print( line )