知识点:
1.文件写 f= open("backup.data","w")
b=f.write(str(a)) a为列表 这里需要将列表转为字符串
f.close()
2.文件:f = open("backup.data","r")
b= eval(f.read()) 这里需要用eval函数进行转换 文件怎么存的 文件就怎么读
f.close()
3.最好将文件加载放在
try:
pass
except Exception:
pass
中,因为若是没有.data 文件,程序不会崩掉。
#用户提示
print(" 名片管理系统")
print("*"*10)
print("1.打印所有名片信息")
print("2.查询某人名片信息")
print("3.修改某人名片信息")
print("4.添加某人名片信息")
print("5.删除某人名片信息")
print("6.退出系统")
print("7.保存到文件")
print("*"*10)
#字典嵌套在列表中
name_dict = [{"name":"花花","addr":"地球","age":18},{"name":"天天","addr":"月球","age":19}]
try:
f = open("backup.data", "r")
name_dict = eval(f.read())
f.close()
print("加载成功!")
except Exception:
print("加载失败!")
#用户输入
while True:
#str_name = ""
#str_num = ""
str_num = int(input("请输入查询序号"))
#打印列表
if str_num == 1:
for temp in name_dict:
print("name:%s,addr:%s,age:%d"%(temp["name"],temp["addr"],temp["age"]))
print("打印完成")
#打印某个人信息
elif str_num == 2:
src_flag = 0
str_name = input("请输入姓名")
for temp in name_dict:
#print(temp.get('name'))
# print(temp['name']) for test
# print(str_name)
if temp['name'] == str_name:
print("name:%s,addr:%s,age:%d" % (temp["name"], temp["addr"], temp["age"]))
#print(temp.get('name'),temp.get('addr'),temp.get('age'))
src_flag = 1
break
if src_flag == 1:
print("查询完成")
else:
print("查无此人")
#修改某个人信息
elif str_num == 3:
temp_dict = {}
str_name = input("请输入姓名")
for temp in name_dict:
if temp["name"] == str_name:
str_addr = input("请输入地址")
str_age = int(input("请输入年龄"))
temp["addr"] = str_addr
temp["age"] = str_age
print("修改完成")
break
else:
print("没有找到此人name 无法修改")
#添加某个人信息
elif str_num == 4:
temp_dict = {}
str_name = input("请输入姓名")
str_addr = input("请输入地址")
str_age = int(input("请输入年龄"))
temp_dict["name"] = str_name
temp_dict["addr"] = str_addr
temp_dict["age"] = str_age
name_dict.append(temp_dict)
print(name_dict)
print("添加成功")
#删除某个人信息
elif str_num == 5:
str_name = input("求输入姓名")
for temp in name_dict:
if temp["name"] == str_name:
name_dict.remove(temp)
print("删除成功")
break;
else:
print("删除失败,可能是因为没有此人")
#退出
elif str_num == 6:
break;
elif str_num == 7:
f = open("backup.data","w")
f.write(str(name_dict))
f.close()
print("保存成功")
else:
pass
print("程序已退出")