Python-Day8-文件操作 编码转换
#读取字符 f=open('Test.txt',mode='r',encoding='utf-8') # 路径 模式r只读 编码方式 c=f.read()#读文件 print(c,type(c))#哈哈哈哈哈,你好呀 类型str #<class 'str'> f.close()#关闭文件 #读取字节 f=open('Test.txt',mode='rb') # 路径 模式rb读取字节 c=f.read()#读文件 print(c,type(c))#b'\xe5\x93\x88\xe5\x93\x88\xe5\x93\x88\xe5\x93\x88\xe5\x93\x88\xef\xbc\x8c\xe4\xbd\xa0\xe5\xa5\xbd\xe5\x91\x80' # <class 'bytes'> f.close()#关闭文件
#只写字符 f=open('log',mode='w',encoding='utf-8') f.write('hhhhh哈哈') f.close() #只写字节 f=open('log',mode='wb') f.write('hhhhh哈哈'.encode('utf-8')) f.close()
#读写字符 f=open('log',mode='r+',encoding='utf-8') c=f.read() f.write('hhhhhax') print(c) f.close() #读写字节 f=open('log',mode='r+b') c=f.read() f.write('hhhhhax'.encode('utf-8')) print(c) f.close()
#写读字符 f=open('log',mode='w+',encoding='utf-8') f.write('hhhhhax') f.seek(0)#调光标 print(f.read())#hhhhhax f.close() #写读字节 f=open('log',mode='w+b') f.write('hhhhhax'.encode('utf-8')) f.seek(0)#调光标 print(f.read())#b'hhhhhax' f.close()
#追加 f=open('log',mode='a',encoding='utf-8') f.write('哈哈') f.close() #追加 (加光标后可读写) f=open('log',mode='a+',encoding='utf-8') f.write('hhhhhax西') f.seek(0)#调光标 print(f.read()) f.close()
#功能详解 #文件内容: 哈1哈2哈3哈 f=open('log',mode='r+',encoding='utf-8') # c=f.read(3)#哈1哈 读出来的都是字符 f.seek(3)#seek是按照字节定光标 一个中文三字节 一个英文一字节 #print(f.read())#哈2哈3哈 print(f.tell())#显示光标位置 15 print(f.readable())#判断是否可读 True print(f.seekable())#判断是否可以获取光标 True print(f.writable())#判断是否可写 True # line=f.readline()#读一行 # print(line)#1哈2哈3哈 line=f.readlines() #读取多行并转换成列表 print(line)#['1哈2哈3哈\n', 'dddddd'] #文件内容 abcdef f.truncate(4) #截取 截完之后编程abcd f.close() #输出文件全部内容 with open('log',mode='r+',encoding='utf-8') as obj,\ open('Test.txt',mode='r+',encoding='utf-8') as obj2: print(obj.read()) print(obj2.read())
print('注册系统') UserName=input('请输入账号:') PassWord=input('请输入密码:') with open('User',mode='w',encoding='utf-8')as f: f.write('{}\n{}'.format(UserName,PassWord)) print('注册成功') lis=[]#接收读出的账号密码 i=0 #统计登录次数 print('登录系统') while i<3: UserNames = input('请输入账号:') PassWords = input('请输入密码:') with open('User', mode='r+', encoding='utf-8')as f1: for line in f1: lis.append(line) if UserNames==lis[0].strip() and PassWords==lis[1].strip(): print('登录成功') break else: print('登录失败') i+=1
# str --->byte encode 编码 s = '二哥' b = s.encode('utf-8') print(b)#b'\xe4\xba\x8c\xe5\x93\xa5' #byte --->str decode 解码 s1 = b.decode('utf-8') print(s1)#二哥 s = 'abf' b = s.encode('utf-8') print(b)#b'abf' #byte --->str decode 解码 s1 = b.decode('gbk') print(s1)#abf
with open('Test1.txt',mode='r',encoding='utf-8')as f,open('Test1.bak',mode='w',encoding='utf-8')as f2: for line in f: if '沙雕' in line: line=line.replace('沙雕','**') f2.write(line) import os os.remove('Test1.txt')#删除原文件 os.rename('Test1.bak','Test1.txt')优质内容筛选与推荐>>