通过一个例子来熟悉文件的基本操作:创建文件,读取文件,修改文件,删除文件,重命名文件,判断文件是否存在
1 ''' 2 编写可供查询的员工信息表--学号 姓名 年龄 班级 3 1. 提供格式化查询接口 4 2. 允许用户添加或者删除员工信息 5 ''' 6 import os 7 employee_dir = 'employee_list' 8 index=employee_dir+"/index" 9 10 11 if(not os.path.exists(employee_dir)): 12 os.mkdir(employee_dir,777) 13 14 def add_student(id,name,age,_class): 15 local_file = employee_dir+"/"+str(id) 16 if(os.path.isfile(local_file)): 17 print("id: %s 已经存在,请重新添加" %(id)) 18 else: 19 f=open(local_file,"w") 20 f.write(name+" "+str(age)+" "+_class) 21 f.close() 22 f=open(index,"a") 23 f.write(str(id)+" "+name+" ") 24 f.close() 25 print("id=%s添加成功" %id) 26 27 def select_student(**kwargs): 28 for key in kwargs.keys(): 29 if(key=='id'): 30 local_file = employee_dir+"/"+str(kwargs[key]) 31 if(not os.path.isfile(local_file)): 32 print("不存在id:",kwargs[key]) 33 else: 34 f=open(local_file,"r") 35 print(kwargs[key],f.read()) 36 elif(key=='name'): 37 if(not os.path.isfile(index)): 38 print("不存在name:",kwargs[key]) 39 else: 40 i=0 41 f=open(index,"r") 42 for line in f.readlines(): 43 id,name = line.strip().split(" ") 44 if(name == kwargs[key]): 45 i=i+1 46 select_student(id=id) 47 if(i==0): 48 print("不存在name:",kwargs[key]) 49 else: 50 print("无效的获取方式,只能通过id和name来获取!") 51 52 53 def modify_student(id,name,age,_class): 54 local_file = employee_dir+"/"+str(id) 55 if(os.path.isfile(local_file)): 56 os.remove(local_file) 57 rm_line(index,id) 58 add_student(id,name,age,_class) 59 print("id=%s修改成功" %id) 60 else: 61 print("id: %s 不存在,请先添加" %(id)) 62 63 def delete_student(**kwargs): 64 for key in kwargs.keys(): 65 if(key=='id'): 66 local_file = employee_dir+"/"+str(kwargs[key]) 67 if(not os.path.isfile(local_file)): 68 print("不存在id:",kwargs[key],",无法删除") 69 else: 70 os.remove(local_file) 71 rm_line(index,kwargs[key]) 72 print("删除id=%s成功" %kwargs[key]) 73 elif(key=='name'): 74 if(not os.path.isfile(index)): 75 print("不存在name:",kwargs[key],",无法删除") 76 else: 77 i=0 78 f=open(index,"r") 79 for line in f.readlines(): 80 id,name = line.strip().split(" ") 81 if(name == kwargs[key]): 82 i=i+1 83 delete_student(id=id) 84 if(i==0): 85 print("不存在name:",kwargs[key],",无法删除") 86 else: 87 print("无效的删除方式,只能通过id和name来删除!") 88 89 def rm_line(file,id): 90 if(not os.path.isfile(file)): 91 print("不存在文件:",file) 92 else: 93 f= open(file,"r") 94 of = open(file+".tmp","w") 95 for line in f.readlines(): 96 localid,localname = line.strip().split(" ") 97 if(str(id)==localid): 98 pass 99 else: 100 of.write(line,) 101 f.close() 102 of.close() 103 if(os.path.isfile(file+".tmpt")): os.remove(file+".tmpt") 104 os.rename(file,file+".tmpt") 105 os.rename(file+".tmp",file)