open函数
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
file: 必需,文件路径(相对或者绝对路径)。
mode: 可选,文件打开模式
buffering: 设置缓冲
encoding: 一般使用utf8
errors: 报错级别
newline: 区分换行符
closefd: 传入的file参数类型
with open('test.txt', encoding='utf-8') as test:
contents = test.read()
print(contents)
学过其他语言的小伙伴应该知道open和close是一对好伙伴,但是这里只用了open,因为with在不需要访问文件后会将其关闭,减小了bug出现后,无法close的现象。
写入文件
# r是只读模式,w是写入模式,a是附加模式,r+是读取和写入,默认只读
filename = 'test.txt'
with open(filename, 'w') as filena:
filena.write('i love python')
a是附加模式,意思是将话添加到文本的末尾