python之路——8
王二学习python的笔记以及记录
学习内容
.1.文件操作
笔记.txt
1.文件路径:D:\python\Day8\笔记.txt
2.编码方式:GB2312
3.操作方式:只读,只写,追加,读写,写读...
以什么编码方式储存文件,就以什么编码进行操作
2. 各种操作 r w a r+ a+ w+
代码区
1.文件操作练习

# 只读文件 r ''' # 非文字文件 用rb f = open('d:\python\Day8\笔记.txt', mode='r', encoding='GB2312') content = f.read() print(content, type(content)) f.close() ''' # 只写文件 w ''' # w 没有文件,创建文件;有文件,删除内容再写入 f = open('log', mode='w', encoding='utf-8') f.write('大萨达所') f.close() # wb f = open('log', mode='wb',) f.write('dsadsasds所'.encode('utf-8')) f.close() ''' # 增加内容 a a+ 增读 ''' 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='a+', encoding='utf-8') f.write('增加内容') f.seek(0) print(f.read()) f.close() ''' # 读写(r+ 读写顺序不要乱) 文件 ''' f = open('log', mode='r+', encoding='utf-8') print(f.read()) f.write('呦西') f.close() f = open('log', mode='r+b') print(f.read()) f.write('呦西'.encode('utf-8')) f.close() ''' # 写读(w+ 写读顺序不要乱) 文件 ''' f = open('log', mode='w+', encoding='utf-8') f.write('呦西') f.seek(0) print(f.read()) f.close() f = open('log', mode='w+b') f.write('呦西'.encode('utf-8')) f.seek(0) print(f.read()) f.close() ''' # 功能详解 # 按照最小字符去读 seek 是按照字节定义光标,unicode 中一个中文=3字节 ''' f = open('log', mode='r+', encoding='utf-8') f.seek(3) print(f.tell()) print(f.read()) f.close() ''' # tell 使用 无论怎么调节光标a操作直接增加到最后 ''' f = open('log', mode='a+', encoding='utf-8') f.write('增加内容') count = f.tell() f.seek(count - 3) print(f.read()) f.close() ''' # 命令 ''' f.tell() f.readable() # 是否可读 f.readline() # 一行一行读 f.readlines() # 将每行当成列表中的一个元素 f.truncate(6) #对源文件进行截取 按字节 for line in f: print(line) # 循环打印源文件 with open('log', mode='r+', encoding='utf-8') as f: print(f.read()) with open('log', mode='r+', encoding='utf-8') as f, open('笔记.txt', mode='r+', encoding='GB2312') as f1: print(f1.read()) # 同时打开多个 '''
2.用户注册,登陆,三次机会
# 用户注册,并登录,三次机会 print('欢迎注册') account = input('请输入用户名') answer = input('请输入密码') with open('log', mode='w+', encoding='utf-8') as f: f.write(account+'\n') f.write(answer) print('注册成功,请登录') li = [] with open('log', mode='r+', encoding='utf-8') as f1: for line in f1: li.append(line) count = 3 while count >= 1: count = count - 1 acc = input('请输入账号') if acc == li[0].strip(): count = 3 while count >= 1: count = count - 1 ans = input('请输入密码') if ans == li[1].strip(): print('正在登陆请稍后') quit() else: print('密码错误,剩余次数', count) continue else: print('账号输入错误,剩余次数',count) if count == 0: print('机会用完啦,明天再来吧') break continue