1文件操作
文件路径:d:\
编码方式:utf-8、gbk..
操作方式:只读,只写。追加,读写,写读....
以什么编码方式储存的文件,就以什么编码方式打开
1打开文件
2进行读写操作
3输出
4关闭文件
只读:r、rb
# f = open('hello','r',encoding='utf-8')
# content = f.read()
# print(content)
# f.close()
# f = open('hello','rb')
# content = f.read()
# print(content)
# f.close()
# f = open('hello','r',encoding='utf-8')
# content = f.read()
# print(content,type(content))
# f.close()
只写:w wb没有此文件时,会自动创建一个文件
若有此文件,write()操作会删除原文件内容,再写
# f = open('log','w',encoding='utf-8')
# content = f.write('规范化')
# f.close()
f = open('log','wb')
content = f.write('施加'.encode('utf-8'))
f.close()
追加 a、ab
f = open('log','a',encoding='utf-8')
f.write('\tdfg')
f.close()
f = open('log','ab')
f.write('\tdfg'.encode('utf-8'))
f.close()
读写 r+ 、r+b只能读 写。
f = open('log','r+',encoding='utf-8')
print(f.read())
f.write('\n排列\n pl')
f.close()
若先写后读,光标会在最开始
f = open('log','r+b')
print(f.read())
f.write('\n排列\n pl'.encode('utf-8'))
f.close()
写读 w+、 w+b
f = open('log','w+',encoding='utf-8')
con = f.write('\n排列\n pl')
f.seek(0)
print(f.read())
f.close()
seek()调节光标
tell()光标所在位置
f = open('log','r+',encoding='utf-8')
f.seek(3)
print(f.tell())#3
追加 a+
f = open('log','a+',encoding='utf-8')
f.write('\n排列\n pl')
f.seek(0)
print(f.read())
f.close()
功能详解
f = open('log','r+',encoding='utf-8')
con = f.read(3) #读取三个
print(con)
f.close()#qaa
f = open('log','r+',encoding='utf-8')
f.seek(3) seek按字节来定光标位置
con = f.read(3)
print(con)
f.close()#化对按
seek()调节光标
tell()光标所在位置
readable()是否可读
truncate()截取
readline()一行一行地读
line = f.readline()
print(line)
f.close()#附近的人,二哥,,唇膏,现已,班长
readlines()每一行当成列表中的一个元素,添加到list中
line = f.readlines()
print(line)
f.close()#['附近的人,二哥,,唇膏,现已,班长\n', '双速度,是滴']
with open()
with open('log','r+',encoding='utf-8') as f: print(f.read())