写
只写
# 只写 # 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()
写读
# 读写 f = open('us', mode='w+', encoding='utf-8') f.write('信念和勇气') print(f.read()) # 空白 f.close()
光标定位
# 读写 f = open('us', mode='r+', encoding='utf-8') f.write('信念和勇气') f.seek(0) print(f.read()) f.close()
读
只读
# 只读 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()
按照字符开始读
# 读写 f = open('us', mode='r+', encoding='utf-8') f.write('信念和勇气') print(f.read(3)) f.close()
按照字节定光标 / 前往后
# 读写 f = open('us', mode='r+', encoding='utf-8') f.write('新年贺卡') f.seek(3) print(f.read()) f.close()
定光标 + 读 / 后往前
# 定光标,读特定数目字符 f = open('us', mode='r+', encoding='utf-8') f.write('新年贺卡恭喜发财') count = f.tell() f.seek(count-9) print(f.read(1)) f.close()
读写
# 读写 f = open('us', mode='r+', encoding='utf-8') print(f.read()) f.write('信念和勇气') f.close()
追加
# 追加 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()
推荐读写方式
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)
用文件读写的方式登陆用户
# 文件读写方式登陆用户,三次机会 username = 'xiaozhao' password = '20181009' with open('us', mode='w', encoding='utf-8') as f: f.write('{} {}'.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('登陆失败')