1、使用open内置函数打开一个文件
file:相对路径或者绝对路径
mode:文件的模式。 r 只读 w只写 b:二进制 t:以文本形式打开等等
encoding:编码方式,windows下默认为gbk
例子:
读文件的例子
file=open('./a.txt',encoding='utf8')print(file.read())#读取整个文件,#print(file.read(10))#read可以指定读取的长度,一般建议使用指定长度的方式,否则cpu可能运行很长时间
file.close()
file=open('./a.txt',encoding='utf8')whileTrue:
content=file.readline()print(content)#每次只读取一行
if content == '':breakfile.close()
file=open('./a.txt',encoding='utf8')
content= file.readlines()#读取所有文件,并以每一行为单位放在一个列表里
print(content)
file.close()
推荐的读
file=open('./a.txt',encoding='utf8')whileTrue:
content= file.read(1024)#每次读1024个长度
print (content)#读取整个文件
if notcontent:brea