python学习之老男孩python全栈第九期_day008知识点总结

'''
'如何打开一个文件
模特主妇护士老师.txt
1. 文件路径:f:\模特主妇护士老师.txt
2. 操作方式:只读:r ,rb ,只写: w, wb ,追加: a , ab,读写:r+ , r+b,写读 :w+ , w+b ......
3. 编码方式

以什么编码方式储存的文件,就以什么编码打开进行操作

'''

绝对路径: 从根目录开始
f = open('f:\模特主妇护士老师.txt', mode = 'r', encoding = 'utf-8')
content = f.read()
print(content)
f.close()

相对路径: 从当前目录开始

只读 r

bytes --> str
f = open('模特主妇护士老师.txt', mode = 'r', encoding = 'utf-8')
content = f.read()
print(content,type(content))
f.close()


f = open('模特主妇护士老师.txt', mode = 'rb')
content = f.read()
print(content)
f.close()

对于写 w ,没有此文件就会创建文件

f = open('log', mode = 'w', encoding = 'utf-8')
f.write('骑兵步兵')
f.close()

先将源文件的内容全部清除,再进行写操作

f = open('log', mode = 'w', encoding = 'utf-8')
f.write('回房间ask东方航空')
f.close()

f = open('log', mode = 'wb')
f.write('回房间ask东方航空'.encode('utf-8'))
f.close()

追加

f = open('log', mode = 'wb')
f.write('回房间ask东方航空'.encode('utf-8'))
f.close()

追加

f = open('log',mode = 'a', encoding = 'utf-8')
f.write('kidd')
f.close()

f = open('log',mode = 'a+', encoding = 'utf-8')
f.write('kidd')
f.seek(0) # + 可以用seek(),寻找光标
print(f.read())
f.close()

f = open('log',mode = 'ab')
f.write('KID'.encode('utf-8'))
f.close()

读写

f = open('log', mode = 'r+', encoding = 'utf-8')
print(f.read())
f.write('尹宁')
print(f.read())
f.close()

写读

r+ 模式下 进行写读,从头开始写

f = open('log', mode = 'r+', encoding = 'utf-8')
f.write('KID')
print(f.read())
f.close()

f = open('log', mode = 'r+', encoding = 'utf-8')
f.write('KIDDDDDDDD')
print(f.read())
f.close()

读写

# 后面加 b , 就不写encoding = ''了

f = open('log', mode = 'r+b')
print(f.read())
f.write('尹宁'.encode('utf-8'))
f.close()

写读 w+

f = open('log', mode = 'w+', encoding = 'utf-8')
f.write('KID')
f.seek(0)
print(f.read())
f.close()

功能详解
最常用的就是r+

read()、seek()、

f = open('log', mode = 'r+', encoding = 'utf-8')
# content = f.read(3) # 读出前三个字符(读出来的都是字符)
f.seek(3) #移动光标是按照字节定光标的位置,一个中文是三个字节,故只能是3 的倍数
print(f.tell()) # 告诉你光标的位置
# content = f.read()
# print(content)
f.close()

f = open('log',mode = 'a+', encoding = 'utf-8')
f.write('kidd')
content = f.tell()
f.seek(content - 3) # 中文是一个字符(三个字节),英文是三个字符(三个字节)
print(f.read())
f.close()

f = open('log', mode = 'r+', encoding = 'utf-8')
f.tell()
f.readable() #是否可读
line = f.readline() # 一行一行的读
line = f.readlines() # 每一行当成列表中的一个元素,添加到list中(for循环)
f.truncate(4)
print(l1)
for line in f:
print(line)
f.close()

with open('log', mode = 'r+', encoding = 'utf-8') as obj:
print(obj.read()) # close() 不用写,自动关闭

with open('log', mode = 'r+', encoding = 'utf-8') as f1,open('log', mode = 'r+', encoding = 'utf-8') as f2:
print(f1.read()) # 可以打开多个
print(f2.read())

posted @ 2018-07-08 19:08  李培冠  阅读(381)  评论(0编辑  收藏  举报