1. 文件打开模式html
2. 文件操做方法python
文件读写与字符编码app
以读取为例,这样一个文件:text.txt, 该文件的字符编码为 utf-8ide
总有一天总有一年会发现 有人默默的陪在你的身边 也许 我不应在你的世界 当你收到情书 也表明我已经走远
1. 基本实现编码
f = open('text.txt', 'r', encoding='utf-8') print(f.read()) f.close()
2. 中级实现spa
在基本实现的的基础上,可能要考虑到一些可能出现的意外因素。由于文件读写时都有可能产生IO错误(IOError),一旦出错,后面包括 f.close() 在内的全部代码都不会执行了,所以咱们要保证文件不管如何都应该关闭。3d
f = '' # 全局要申明下 f 变量,否则 f.close() 会报黄 try: f = open('text.txt', 'r', encoding='utf-8') print(f.read()) finally: if f: f.close()
在上面的代码中,就是 try 中的代码出现了报错,依然会执行 finally 中的代码,即文件关闭操做被执行。code
3. 最佳实践htm
为了不忘记或者为了不每次都要手动关闭文件,且过多的代码量,咱们可使用 with 语句,with 语句会在其代码块执行完毕以后自动关闭文件。blog
with open('text.txt', 'r', encoding='utf-8') as f: print(f.read()) print(f.closed) # 经过 closed 获取文件是否关闭,True关闭,False未关闭 # 执行结果: # 总有一天总有一年会发现 # 有人默默的陪在你的身边 # 也许 我不应在你的世界 # 当你收到情书 # 也表明我已经走远 # True
要求:
1. 用户可注册不一样的帐户,并将用户信息保存到本地文件中;
2. 下次登陆,注册过的用户均可实现登陆
代码:
#!/usr/bin/python3 # -*- coding: utf-8 -*- # Author: hkey import os def file_oper(file, mode, *args): if mode == 'r': list_user = [] with open(file, mode) as f: for line in f: list_user.append(line.strip()) return list_user elif mode == 'a+': data = args[0] with open(file, mode) as f: f.write(data) class User(object): def __init__(self, name, passwd): self.name = name self.passwd = passwd self.file = 'user.db' def regist(self): data = '%s|%s\n' % (self.name, self.passwd) file_oper(self.file, 'a+', data) if os.path.isfile('user.db'): print('\033[32;1m注册成功.\033[0m') def login(self): list_user = file_oper(self.file, 'r') print('list_user:', list_user) user_info = '%s|%s' % (self.name, self.passwd) if user_info in list_user: print('\033[32;1m登陆成功.\033[0m') else: print('\033[31;1m登陆失败.\033[0m') def start(): while True: print('1. 注册\n' '2. 登陆\n' '3. 退出') choice = input('\033[34;1m>>>\033[0m').strip() if choice == '1': username = input('\033[34;1musername:\033[0m').strip() password = input('\033[34;1mpassword:\033[0m').strip() user = User(username, password) user.regist() elif choice == '2': username = input('\033[34;1musername:\033[0m').strip() password = input('\033[34;1mpassword:\033[0m').strip() user = User(username, password) user.login() elif choice == '3': break else: print('\033[31;1m错误:输入序号错误。\033[0m') if __name__ == '__main__': start()
更多参考连接:https://www.cnblogs.com/yyds/p/6186621.html