1.编写一个统计指定文件类型的脚本工具
输入指定类型的文件后缀
eg:.txt
并给出一个具体路径 之后统计该类型文件在该文件下的个数
ps:简单实现即可 无需优化
import os
targht_path = input('目录路径:').strip()
targht_back = input('目标路径:').strip()
file_name_list = os.listdir(targht_path)
count = 0
for file_name in file_name_list:
if file_name.endswith(targht_back):
count +=1
print(f'目录{targht_path}下后缀名为{targht_back}的文件数目有:{count}')
2.针对json实操 尝试单文件多用户(一行一个)是否可实现>>>:哪个更方便
不要求完成 单纯体会两种思路的难易
import json
d={'name':'kevin','pwd':'123'}
with open(r'userinfo.json','a',encoding='utf8')as f:
res= json.dumps(d)
f.write(res)
f.write('\n')
with open(r'userinfo.json','r',encoding='utf8')as f:
for line in f:
new_list = line.strip('\n')
res = json.loads(new_list)
print(res, type(res))
针对JSON格式数据单文件单用户更方便一些
3.编程小练习
有一个目录文件下面有一堆文本文件
eg:
db目录
J老师视频合集
R老师视频合集
C老师视频合集
B老师视频合集
文件内容自定义即可 要求循环打印出db目录下所有的文件名称让用户选择
用户选择哪个文件就自动打开该文件并展示内容
涉及到文件路径全部使用代码自动生成 不准直接拷贝当前计算机固定路径
import os
base_dir = os.path.dirname(__file__)
db_dir = os.path.join(base_dir, 'bbb')
file_name_list = os.listdir(db_dir)
while True:
for i, j in enumerate(file_name_list, start=1):
print(i, j)
file_num = input('请输入您想要打开的文件编号>>>:').strip()
if not file_num.isdigit():
print('文件编号只能是数字')
continue
file_num = int(file_num)
if file_num not in range(1, len(file_name_list) + 1):
print('文件编号超出了范围')
continue
file_name = file_name_list[file_num - 1]
file_path = os.path.join(db_dir, file_name)
with open(file_path, 'r', encoding='utf8') as f:
print(f.read())
4.周末大作业(尝试编写)
项目功能
1.用户注册
2.用户登录
3.添加购物车
4.结算购物车
项目说明
用户数据采用json格式存储到文件目录db下 一个用户一个单独的文件
数据格式 {"name":"jason","pwd":123}
用户注册时给每个用户添加两个默认的键值对(账户余额 购物车)
{"balance":15000,"shop_car":{}}
添加购物车功能 商品列表可以自定义或者采用下列格式
good_list = [
['挂壁面',3]
['印度飞饼', 22]
['极品木瓜', 666],
['土耳其土豆', 999],
['伊拉克拌面', 1000],
['董卓戏张飞公仔', 2000],
['仿真玩偶', 10000]
]
用户可以反复添加商品,在购物车中记录数量
{'极品木瓜':[个数,单价]}
结算购物车
获取用户购物车中所有的商品计算总价并结算即可
针对添加购物车和结算只有登录的用户才可以执行
import json
import os
base_dir = os.path.dirname(__file__)
db_dir = os.path.join(base_dir, 'db')
if not os.path.exists(db_dir):
os.mkdir(db_dir)
is_login = {
'username': '',
}
def login_auth(func_name):
def inner(*args, **kwargs):
if is_login.get('username'):
res = func_name(*args, **kwargs)
return res
else:
print('请先登录')
login()
return inner
def register():
while True:
username = input('username>>>:').strip()
password = input('password>>>:').strip()
confirm_pwd = input('confirm_pwd>>>:').strip()
if not password == confirm_pwd:
print('两次密码不一致')
continue
file_path = os.path.join(db_dir, '%s.json' % username)
if os.path.exists(file_path):
print('用户名已存在')
continue
temp_user_dict = {
'name': username,
'pwd': password,
'balance': 15000,
'shop_car': {}
}
with open(file_path, 'w', encoding='utf8') as f:
json.dump(temp_user_dict, f)
print(f'用户{username}注册成功')
return
def login():
while True:
username = input('username>>>:').strip()
password = input('password>>>:').strip()
file_path = os.path.join(db_dir, '%s.json' % username)
if not os.path.isfile(file_path):
print('用户名不存在')
continue
with open(file_path, 'r', encoding='utf8') as f:
user_dict = json.load(f)
if password == user_dict.get('pwd'):
is_login['username'] = user_dict.get('name')
print('登录成功')
return
else:
print('密码错误')
@login_auth
def add_shop_car():
good_list = [
['挂壁面', 3],
['印度飞饼', 22],
['极品木瓜', 666],
['土耳其土豆', 999],
['伊拉克拌面', 1000],
['董卓戏张飞公仔', 2000],
['仿真玩偶', 10000]
]
temp_shop_dict = {}
while True:
for i, j in enumerate(good_list):
print(f"商品编号:{i} | 商品名称:{j[0]} | 商品单价:{j[1]}")
target_good_id = input('请输入想要购买的商品编号(q)>>>:').strip()
if target_good_id == 'q':
file_path = os.path.join(db_dir, '%s.json' % is_login.get('username'))
with open(file_path, 'r', encoding='utf8') as f:
user_dict = json.load(f)
old_shop_car = user_dict.get('shop_car')
for good_name in temp_shop_dict:
if good_name in old_shop_car:
old_shop_car.get(good_name)[0] += temp_shop_dict.get(good_name)[0]
else:
old_shop_car[good_name] = temp_shop_dict.get(good_name)
user_dict['shop_car'] = old_shop_car
with open(file_path, 'w', encoding='utf8') as f:
json.dump(user_dict, f)
print('添加购物车成功')
return
if not target_good_id.isdigit():
print('商品编号只能是数字')
continue
target_good_id = int(target_good_id)
if target_good_id not in range(len(good_list)):
print('商品编号超出了范围')
continue
target_good_info = good_list[target_good_id]
target_good_name = target_good_info[0]
target_good_price = target_good_info[1]
target_good_num = input('请输入想要购买的商品数量>>>:').strip()
if not target_good_num.isdigit():
print('商品数量只能是数字')
continue
target_good_num = int(target_good_num)
if target_good_name in temp_shop_dict:
value_list = temp_shop_dict.get(target_good_name)
value_list[0] += target_good_num
temp_shop_dict[target_good_name] = value_list
else:
temp_shop_dict[target_good_name] = [target_good_num, target_good_price]
@login_auth
def buy_shop_car():
file_path = os.path.join(db_dir, '%s.json'%(is_login.get('username'),))
with open(file_path, 'r', encoding='utf8') as f:
user_dict = json.load(f)
shop_car = user_dict.get('shop_car')
if not shop_car:
print('你先去买东西 行不行')
return
total_money = 0
current_balance = user_dict.get('balance')
for values in shop_car.values():
total_money += values[0] * values[1]
if current_balance >= total_money:
rest_money = current_balance - total_money
user_dict['balance'] = rest_money
user_dict['shop_car'] = {}
with open(file_path, 'w', encoding='utf8') as f:
json.dump(user_dict, f)
print(f'今日消费:{total_money} 卡上余额:{rest_money}')
else:
print('你个穷逼 钱不够')
return
func_dic = {
'1': register,
'2': login,
'3': add_shop_car,
'4': buy_shop_car
}
while True:
print("""
1.注册功能
2.登录功能
3.添加购物车
4.结算购物车
""")
choice = input('请输入功能编号>>>:').strip()
if choice in func_dic:
func_dic.get(choice)()
else:
print('输入不合法')