python笔记8—day8

知识点

1、文件的操作   只读、只写、追加、读写、写读

1.1、只读 r rb

#相对路径读取文件里的内容
x=open('001',mode='r',encoding='utf-8')#文件001里写有详细信息显示
content=x.read()
print(content)#结果为 详细信息显示
x.close()
#绝对路径读取文件里的内容
x=open('d:\\123.txt',mode='r',encoding='utf-8')#文件123.txt里写有大街上开飞机的咖啡机
content=x.read()
print(content)#结果为 大街上开飞机的咖啡机
x.close()

#rb
x=open('001',mode='rb')
content=x.read()
print(content)#结果为b'\xe8\xaf\xa6\xe7\xbb\x86\xe4\xbf\xa1\xe6\x81\xaf\xe6\x98\xbe\xe7\xa4\xba'
# x.close()

1.2、只写 w wb

#w 没有此文件就创建文件,如果有文件就删除源文件内容,在写新的内容
x=open('002',mode='w',encoding='utf-8')
x.write('恭喜您创建了一个002文件')
x.close()

x=open('002',mode='w',encoding='utf-8')
x.write('删除源文件内容删除,在写新的内容')
x.close()

#wb
x=open('002',mode='wb')
x.write('恭喜您创建了一个002文件'.encode('utf-8'))
x.close()

1.3、追加 a ab

#a 在后面追加
x=open('002',mode='a',encoding='utf-8')
x.write('kkkkk')
x.close()

#ab 也是在后面追加
x=open('002',mode='ab')
x.write('aaaa'.encode('utf-8'))
x.close()

1.4、读写 r+ r+b

#先读后写:先读取完文件里的内容,然后读到那就在那添加
x=open('001',mode='r+',encoding='utf-8')
print(x.read())
x.write('恭喜您!')
x.close()
#先写后读:先写完你要写的东西先写,他会覆盖原有的内容,然后把没覆盖的内容再读出来 x=open('001',mode='r+',encoding='utf-8') x.write('恭喜您!') print(x.read()) x.close()
#r+b 跟r+一样,但它读取的是bytes类型 x=open('001',mode='r+b') print(x.read()) x.write('bbb'.encode('utf-8')) x.close()

1.5、写读 w+ w+b

x=open('002',mode='w+',encoding='utf-8')
x.write('啊大苏打')
x.seek(0)
print(x.read())
x.close()

x=open('002',mode='w+b')
x.write('啊大苏打'.encode('utf-8'))
x.seek(0)
print(x.read())
x.close()

2、功能详解

2.1、read 按字符去定光标,然后输出

x=open('001',mode='r',encoding='utf-8')
content=x.read(3)
print(content)#输出的是3个字符
x.close()

2.2、seek 按字节去定光标,然后读取

x=open('001',mode='r',encoding='utf-8')
x.seek(3)
content=x.read()
print(content)
x.close()

2.3、tell 检测光标的位置

x=open('001',mode='r',encoding='utf-8')
x.seek(3)
print(x.tell())
x.close()

2.4、readable 是否可读,返回True或False

x=open('001',mode='r',encoding='utf-8')
print(x.readable())
x.close()

2.5、readline 一行一行的读

x=open('001',mode='r',encoding='utf-8')
print(x.readline())
x.close()

2.6、readlines 每一行都当成列表里的元素,添加到列表

x=open('001',mode='r',encoding='utf-8')
print(x.readlines())
x.close()

2.7、截取

x=open('001',mode='r+',encoding='utf-8')
x.truncate(2)
x.close()

2.8、with open('...',mode='..',encoding='...') as obj  可以不用close()关闭文件,也可以打开多个文件

with open('001',mode='r',encoding='utf-8') as x,\
        open('002', mode='r', encoding='utf-8') as y:
    print(x.read())
    print(y.read())

3、编码和解码

#str --->byte  encode 编码
s = '二哥'
b = s.encode('utf-8')
print(b)
# #byte --->str decode 解码
s1 = b.decode('utf-8')
print(s1)

s = 'abf'
b = s.encode('utf-8')
print(b)
# #byte --->str decode 解码
s1 = b.decode('gbk')
print(s1)
posted @ 2019-08-22 09:56  精灵飞舞之季的低语  阅读(155)  评论(0编辑  收藏  举报