参考一兄弟写的文章进行练习:https://blog.51cto.com/000011211684/2052701
主要目的,熟悉文件列表的增、删、改操作……
# python 3.6 文件打开操作练习
# date:2017-12-26
# _*_ coding:utf-8 _*_
import os,sys
def find():
find_name = input("请输入要查询的员工姓名:").strip().upper()
flag=False
with open("info.txt",'r',encoding='utf-8') as f1:
for line in f1:
if line.split()[0]==find_name:
flag=True
print("员工姓名:",find_name,"\t工资:",line.split()[1])
else:
continue
if not flag:
print("未找到员工信息:\033[31;1m{_name}\033[1m".format(_name=find_name))
def modify():
flag = False
mod_info1=input("请输入要修改的员工姓名:").strip().upper()
with open("info.txt", 'r', encoding='utf-8') as f1 , \
open("info_new", 'w', encoding='utf-8') as f2:
for line in f1:
if mod_info1 ==line.split()[0]:
mod_info2 = input("请输入修改后的工资:").strip()
if not mod_info2.isdigit(): #判断输入是否为数字
print("请输入一个数字!!")
sys.exit() #需等待完善优化,下同
else:
f2.write(mod_info1+'\t'+mod_info2+'\n')
flag = True
else:
f2.write(line)
if os.path.exists('info_bak.txt'):os.remove("info_bak.txt") #如果存在则删除
os.rename("info.txt","info_bak.txt")
os.rename("info_new","info.txt")
if flag:
print("修改成功")
else:
print("未找到员工信息:\033[31;1m{_name}\033[1m".format(_name=mod_info1))
def add():
flag = False
add_info1 = input("请输入要增加的员工姓名:").strip().upper()
with open("info.txt", 'r', encoding='utf-8') as f1 :
for line in f1:
if add_info1 == line.split()[0]:
flag = True
else:
continue
if flag:
print("员工\033[31;1m{_name}\033[1m信息已存在".format(_name=add_info1))
else:
with open("info.txt", 'a', encoding='utf-8') as f2 :
add_info2 = input("请输入工资:").strip()
if not add_info2.isdigit(): # 判断输入是否为数字
print("请输入一个数字!!")
sys.exit()
else:
f2.write(add_info1 + '\t' + add_info2 + '\n')
print("增加成功!!")
def dele():
flag = False
del_info1 = input("请输入要删除的员工姓名:").strip().upper()
with open("info.txt",'r',encoding='utf-8') as f1 ,\
open('info_new','w',encoding='utf-8') as f2:
for line in f1:
if line.split()[0] == del_info1:
flag=True
continue
else:
f2.write(line)
if os.path.exists('info_bak.txt'):os.remove("info_bak.txt") #如果存在则删除
os.rename("info.txt","info_bak.txt")
os.rename("info_new","info.txt")
if flag:
print("删除成功!!")
else:
print("未找到员工信息:\033[31;1m{_name}\033[1m".format(_name=del_info1))
def main():
menu={
'1':find,
'2':modify,
'3':add,
'4':dele,
'5':exit
}
while True:
print("""
请选择:
1,查询员工信息
2,修改员工信息
3,增加员工信息
4,删除员工信息
5,退出系统
""" )
choice=input('>>>>').strip()
if choice in menu:
menu[choice]()
if __name__=="__main__":
main()