python入门_老男孩_文件操作
写
只写
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# 只写 # utf-8 f = open('us', mode='w', encoding='utf-8') f.write('tonight, i can write down the most beautiful lines') f.close # bytes f = open('us', mode='wb') f.write('如果可以'.encode('utf-8')) f.close()
写读
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# 读写 f = open('us', mode='w+', encoding='utf-8') f.write('信念和勇气') print(f.read()) # 空白 f.close()
光标定位
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# 读写 f = open('us', mode='r+', encoding='utf-8') f.write('信念和勇气') f.seek(0) print(f.read()) f.close()
读
只读
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# 只读 f = open('us', mode='r', encoding='utf-8') content = f.read() print(content) f.close() f = open('us', mode='rb') # 以bytes方式,方便传输 content = f.read() print(content, type(content)) f.close()
按照字符开始读
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# 读写 f = open('us', mode='r+', encoding='utf-8') f.write('信念和勇气') print(f.read(3)) f.close()
按照字节定光标 / 前往后
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# 读写 f = open('us', mode='r+', encoding='utf-8') f.write('新年贺卡') f.seek(3) print(f.read()) f.close()
定光标 + 读 / 后往前
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# 定光标,读特定数目字符 f = open('us', mode='r+', encoding='utf-8') f.write('新年贺卡恭喜发财') count = f.tell() f.seek(count-9) print(f.read(1)) f.close()
读写
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# 读写 f = open('us', mode='r+', encoding='utf-8') print(f.read()) f.write('信念和勇气') f.close()
追加
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# 追加 f = open('us', mode='a', encoding='utf-8') f.write('ZHAO') f.close() f = open('us', mode='ab') f.write('ZHAO'.encode('utf-8')) f.close()
推荐读写方式
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
with open('us', mode='r+', encoding='utf-8') as obj: obj.read() print(obj) # 打开多个文件 with open('us', mode='r+', encoding='utf-8') as obj, open('us', mode='r+', encoding='utf-8') as obj1: obj.read() obj1.write('hello,world') print(obj)
用文件读写的方式登陆用户
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# 文件读写方式登陆用户,三次机会 username = 'xiaozhao' password = '20181009' with open('us', mode='w', encoding='utf-8') as f: f.write('{}\n{}'.format(username,password)) i = 0 lis = [] while i < 3: usr = input('请输入用户名:') pwd = input('请输入密码:') with open('us', mode='r', encoding='utf-8') as f: for k in f: lis.append(k) if usr == lis[0].strip() and pwd == lis[1].strip(): print('登陆成功') break else: print('登陆失败')