文件读写
基础操作
- 打开
file = open('1.txt',访问方式,encoding='编码方式')
- 读
text = file.read()
- 关闭
file.close()
访问方式
r:只读
w:只写,如果存在会覆盖,文件不存在创建新文件
a:追加,如果存在指针会放在文件结尾,不存在创建
r+:读写,指针在开头,不存在刨出异常
w+:读写,存在会覆盖,不存在创建
a+读写,指针在结尾,不存在创建
按行读取
text = file.readline().strip()#strip去除结尾换行
for i in file.readlines():
# readlines返回一个可迭代对象并且每个元素都是一行
with结构
with open('xxx.txt') as file1:
text = file1.read()
案例
修改文件
import os with open('a.txt') as read_f,open('a.txt.new','w') as write_f:
data = read_f.read()
data = data.replace('Hello','nihao')
write_f.write(data)
os.remove('a.txt')
os.rename('a.txt.new','a.txt')
计算总价
文件a.txt内容:每一行内容分别为商品名字,价钱,个数。
apple 10 3
tesla 100000 1
mac 3000 2
lenovo 30000 3
chicken 10 3
通过代码,将其构建成这种数据类型:[{'name':'apple','price':10,'amount':3},
{'name':'tesla','price':1000000,'amount':1}......] 并计算出总价钱。
file = open('1.txt','r',encoding='utf-8')
line = []
list = []
for i in file.readlines():
line = i.strip().split(' ')
print(line)
dict = {'name':line[0],'price':line[1],'count':line[2]}
list.append(dict)
print(list)
sum = 0
for i in list:
sum = sum + float(i['price'])*float(i['count'])
print(sum)
file.close()
模拟用户注册登陆
用户的信息需要保存在文件db.txt中
菜单:
供用户 选择时注册还是登陆
注册:
由用户输入用户名和密码
密码必须由字母和数字组成,长度不得小于8位
密码需要输入两次,并且判断密码是否相等,如果不相等注册失败
注册成功的话需要将用户信息写入db.txt中.
登陆:
由用户输入用户名和密码
用户名不存在时返回“用户不存在"
用户名存在密码错误时返回“密码错误”
密码重试超过三次,15秒之内不允许登陆
登陆成功时返回“欢迎登陆成功!”
import re
def SingUp():#注册
file = open('db.txt','a')
username = input('please input your username')
while True:
password = input('please input your password')
passwor2 = input('please input your password once again')
if re.match("^(?:(?=.*[A-Za-z])(?=.*[0-9])).*$",password):
if len(password) >=8:
if password == passwor2:
file.write(f'{username} {password} \n')
print(f'welcom {username}')
break
else:
print('the two password are different!please input again!')
else:
print('your password is too short!')
else:
print('password must have number and words!')
file.close()
def SignIn():#登录
list = []
k = 0
flag = 0
flag1 = 0
file = open('db.txt','r')
cont = file.readlines()
for i in cont:
tmp = i.strip().split(' ')
person = {'username':tmp[0],'password':tmp[1]}
list.append(person)
k += 1
username = input('please input your username')
for i in list:
if username == i['username']:
flag = 1
flag1 = list.index(i)
break
# password = input('please input your password')
# if password == i['password']:
# print(f'hello {username}!')
# else:
# print('wrong password!')
# flag += 1
# if flag > 3:
# break
else:
print('user do not exist!')
break
if flag == 1:
for i in range(3):
password = input('please input your password')
if list[flag1]['password'] == password:
print(f'hello {username}!')
break
else:
print('wrong password!')
file.close()
def Menu():#菜单
print('''
-------------Welcome-------------
Please input a number to choose :
--1. signup--
--2. signin--
---------------------------------
''')
if __name__ == '__main__':
while True:
Menu()
num = input()
if num == '1':
SingUp()
if num == '2':
SignIn()
else:
print('please input a right number!')
加时间戳版本
import re
import time
def SingUp():#注册
file = open('db.txt','a')
username = input('please input your username')
while True:
password = input('please input your password')
passwor2 = input('please input your password once again')
if re.match("^(?:(?=.*[A-Za-z])(?=.*[0-9])).*$",password):
if len(password) >=8:
if password == passwor2:
file.write(f'{username} {password} 0\n')
print(f'welcom {username}')
break
else:
print('the two password are different!please input again!')
else:
print('your password is too short!')
else:
print('password must have number and words!')
file.close()
def SignIn():#登录
list = []
k = 0
flag = 0
flag1 = 0
times = 0
now = time.time()
file = open('db.txt','r')
cont = file.readlines()
for i in cont:
tmp = i.strip().split(' ')
person = {'username':tmp[0],'password':tmp[1],'timemark':float(tmp[2])}
list.append(person)
k += 1
# print(list)
username = input('please input your username')
for i in list:
if username == i['username']:
if ((now - i['timemark']) > 15):
flag = 1
flag1 = list.index(i)
break
else:print('wait! 15s !',now)
else:
if list.index(i) == len(list) - 1:
print('user do not exist!')
break
if flag == 1:
for i in range(3):
password = input('please input your password')
if list[flag1]['password'] == password:
print(f'hello {username}!')
break
else:
times += 1
print('wrong password!')
if times >= 3:
tt = list[flag1]['password']
cont[flag1] = f'{username} {tt} {time.time()}\n'
# print(cont)
with open('db.txt','w') as f:
for i in cont:
f.write(i)
file.close()
def Menu():#菜单
print('''
-------------Welcome-------------
Please input a number to choose :
--1. signup--
--2. signin--
---------------------------------
''')
if __name__ == '__main__':
while True:
Menu()
num = input()
if num == '1':
SingUp()
if num == '2':
SignIn()
else:
print('please input a right number!')
评论已关闭