day8文件操作

# f.seek(6)  #按照字节定光标的位置  严格按照编码方式的字节数调光标 否则报错

# r 只读
# f=open('hhh',mode='r',encoding='utf-8')
# cotent=f.read()
# print(cotent,type(cotent))
# f.close()

#rb bytes类型 不用写编码 用于非文字文件类型打开  上传下载
# f=open('hhh',mode='rb')
# cotent=f.read()
# print(cotent,type(cotent))
# f.close()

# r+ 读写
# f=open('hhh',mode='r+',encoding='utf-8')
# print(f.read())
# f.write('
嘤嘤嘤')   #相当于追加 要先读后写 不然会覆盖
# f.close()

#r+b 读写(以bytes类型)
# f=open('hhh',mode='r+b')
# print(f.read())
# f.write('
大猛,小萌'.encode('utf-8')) #整篇文件用什么编码就用什么编码
# f.close()

#w 只写  没有文件就会创建此文件  #先将原文件的内容全部清空再写
# f = open('hhh1', mode='w',encoding='utf-8')
# f.write('我是个小可爱啊')
# f.close
# print(f.readable())

#wb bytes类型
# f = open('hhh', mode='wb') #先将原文件的内容全部清空再写
# f.write('我是小可爱'.encode('utf-8'))
# f.close

#w+ 写读
# f = open('hhh', mode='w+',encoding='utf-8') #先将原文件的内容全部清空再写
# # f.write('要去洗澡了')
# # f.seek(0)           #按字节把光标移到0的位置 不移动的话光标在最后 没有读取结果
# # print(f.read())
# # f.close
#
#w+b


#a 追加
# f = open('hhh', mode='a',encoding='utf-8')
# f.write("
代码还没敲完a")
# f.close()

#a+ 追加读
# f = open('hhh', mode='a+',encoding='utf-8')
# f.write("
aaaa")
# f.seek(6)  #按照字节定光标的位置  严格按照编码方式的字节数调光标 否则报错
# print(f.read())
# f.close()
#ab

#功能详解
# f = open('hhh', mode='r+',encoding='utf-8')
# f.seek(0)    #?15,16,17都行18不行 换行末尾占一个字符/二个字节??
# print(f.read(4))#按字符阅读  ?4个
# print(f.tell() )#告诉你光标的位置
# print(f.read())
# print(f.readable()) #是否可读  返回一个布尔值
# line=f.readline()#一行一行的读
# # line=f.readlines()#每一行当成list中的一个元素 添加到list中
# # print(f.truncate(6)) #对原文件截取字符 返回截取数
# # print(line)
# f.seek(0)
# # print(f.read())
# for line in f:
#     print(line)
# f.close()
#
# f = open('hhh', mode='a+',encoding='utf-8')
# f.write('假期')
# count=f.tell()
# f.seek(count-9)
# print(f.read(2))
# f.close()

#with 可以同时打开多个文件 在with代码块下操作 不用close  with自动close
# with open('hhh', mode='r+',encoding='utf-8')as f,
#     open('hhh', mode='w+',encoding='utf-8')as f1:
#     f1.write('假期快点来吧!')
#     f1.seek(0)
#     print(f1.read())


# username=input("请输入你的用户名:")
# password=input("请输入你的密码:")
# with open("list_of_info",'w',encoding='utf-8') as f:
#     f.write('%s
%s' % (username,password))
# print("恭喜您,注册成功")
# lis=[]
# i=0
# while i<3:
#     usn=input("请输入你的用户名:")
#     pwd=input("请输入你的秘密:")
#     with open('list_of_info','r+',encoding='utf-8') as f1:
#         for line in f1:
#             lis.append(line)
#             print(line)
#     print(lis)
#     if usn==lis[0].strip() and pwd==lis[1].strip():
#         print("登陆成功")
#         break
#     else:
#         print('账号和密码错误')
#         i+=1
# str---->bytes encode 编码
s='二哥'
b=s.encode('utf-8')
print(b)

# byte---->str  decode 解码
s1=b.decode('utf-8')   #/'gbk'
print(s1)


<<<
b'xe4xbax8cxe5x93xa5'
二哥
原文地址:https://www.cnblogs.com/hi-python/p/10109474.html