1.文件操作
1.文件操作 模特主妇护士老师.txt 1.文件路径:d:\ 模特主妇护士老师.txt 2.编码方式:utf-8 3.操作方式:只读,只写,追加,读写,写读 以什么编码方式储存的,就必须以什么编码方式打开 只读:#bytes——>str # f=open('gcs',mode = 'r',encoding = 'utf-8') # content = f.read() # print(content) # f.close() #rb 是bytes(非文字文件) f=open('gcs',mode = 'rb') content = f.read() print(content,type(content)) f.close() #只写: #对于写,没有此文件就会创建文件 # f=open('log',mode = 'w',encoding = 'utf-8') # f.write('秀秀秀秀') # f.close() #先将源文件的内容全部清除,在写 # f=open('log',mode = 'w',encoding = 'utf-8') # f.write('秀顺') # f.close() #wb bytes # f=open('log',mode = 'wb') # f.write('秀顺'.encode('utf-8')) # f.close() #追加: # f=open('log',mode = 'a',encoding='utf-8') # f.write('在一起') # f.close() f=open('log',mode = 'ab') f.write('可以吗'.encode('utf-8')) f.close() #读写,先读出内容,在写入 # f= open('log',mode='r+',encoding='utf-8') # print(f.read()) # f.write('祝您们幸福') # f.close() #读写的 bytes f= open('log',mode='r+b') print(f.read()) f.write('11111'.encode('utf-8')) f.close()
1 #功能详解 2 3 f=open('gcs',mode = 'r+',encoding = 'utf-8') 4 # content = f.read(3)#读出来的都是字符 5 # f.seek(3)#按字节定光标的位置 6 #f.tell() #告诉你光标位置 7 # f.readable()#可读的 8 # line=f.readline()#一行一行的读 9 # line=f.readlines()#每一行当成列表中的一个元素,添加到列表list 10 11 # f.truncate(3)#在源文件截取 12 # print(line) 13 # for line in f: 14 # print(line) 15 # f.close() 16 # count=f.tell() 17 # f.seek(count-9) 18 # content = f.read(2) 19 # print(content) 20 # f.close() 21 22 # with open('gcs',mode = 'r+',encoding = 'utf-8') as obj: 23 # # obj.read() 24 # print(obj.read()) 25 26 with open('gcs', mode='r+', encoding='utf-8') as obj,\ 27 open('log', mode='r+', encoding='utf-8') as f1: 28 # obj.read() 29 print(obj.read()) 30 print(f1.read())
2.编码
1 2 #str --->byte encode 编码 3 # s = '二哥' 4 # b = s.encode('utf-8') 5 # print(b) 6 # #byte --->str decode 解码 7 # s1 = b.decode('utf-8') 8 # print(s1) 9 10 11 # s = 'abf' 12 # b = s.encode('utf-8') 13 # print(b) 14 # #byte --->str decode 解码 15 # s1 = b.decode('gbk') 16 # print(s1)
3.注册登录
1 username = input('请输入账户名:') 2 passward = input('请输入密码:') 3 with open('f1', mode='w', encoding='utf-8') as obj: 4 obj.write('{}\n{}'.format(username,passward)) 5 print('恭喜您,注册成功!') 6 lis = [] 7 i = 0 8 while i < 3: 9 usn = input("请输入用户名:") 10 pwd = input('请输入密码:') 11 with open('f1', mode='r+', encoding='utf-8') as obj: 12 for line in obj: 13 lis.append(line) 14 if usn == lis[0].strip() and pwd == lis[1].strip(): 15 print('登录成功!') 16 break 17 else: 18 print('账号和密码错误!') 19 i+=1