文件增删改查(加日志记录)有关文件小程序
Posted Wang-Vee
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了文件增删改查(加日志记录)有关文件小程序相关的知识,希望对你有一定的参考价值。
1.
1 1,Alex Li,22,13651054608,IT,2013-04-01 2 2,Jack Wang,30,13304320533,HR,2015-05-03 3 3,Rain Liu,25,1383235322,Saies,2016-04-22 4 4,Mack Cao,40,1356145343,HR,2009-03-01
1 # _*_ coding:utf-8 _*_ 2 import logging 3 logger=logging.getLogger() 4 # 创建一个handler,用于写入日志文件 5 fh = logging.FileHandler(\'work.log\') 6 # 再创建一个handler,用于输出到控制台 7 ch = logging.StreamHandler() 8 formatter=logging.Formatter(\' %(asctime)s-%(name)s\\n%(levelname)s:%(message)s\') 9 fh.setFormatter(formatter) 10 ch.setFormatter(formatter) 11 logger.addHandler(fh) #只使用文件写入 12 logger.setLevel(logging.DEBUG) 13 def info(s): 14 logger.info(s) 15 def error(s): 16 logger.error(s)
1 # _*_ coding:utf-8 _*_ 2 import time,log #自动获取日期 3 staff_table = [] 4 file_path=r\'E:\\PycharmProjects\\qz5\\Day13\\xinxi.txt\' 5 def table_format(): #格式化输出 6 global staff_table 7 for line in staff_table: 8 res = \'%d,%s,%s,%s,%s,%s\\n\' % (line[\'staff_id\'], line[\'name\'], line[\'age\'], line[\'phone\'], line[\'dept\'], line[\'enroll_date\']) 9 yield res 10 def print_table(file_path): #打印表格 11 file_to_date(file_path) 12 for i in table_format(): 13 print(i,end=\'\') 14 def file_to_date(file_path): #读取文件 15 global staff_table 16 staff_table=[{\'staff_id\':int(line.strip().split(\',\')[0]),\'name\':line.strip().split(\',\')[1],\'age\':line.strip().split(\',\')[2],\'phone\':line.strip().split(\',\')[3],\'dept\':line.strip().split(\',\')[4],\'enroll_date\':line.strip().split(\',\')[5]} for line in open(file_path,encoding=\'utf-8\')] 17 def date_to_file(file_path): #写入文件 18 with open(file_path,\'w\',encoding=\'utf-8\') as f: 19 for i in table_format(): 20 f.write(i) 21 def output(line,cmd): #筛选输出 22 for key in line: 23 if key in cmd[0].split(\',\') or cmd[0] == \'*\': 24 print(line[key], end=\' \') 25 print() 26 def select(): #查询功能 可忽略大小写、单双引号 27 print(\'Syntax examples:\\n select name,age from staff_table where age > 22\\n select * from staff_table where dept = \\"IT\\"\\n select * from staff_table where enroll_date like \\"2013\\"\') 28 while True: 29 n=0 30 file_to_date(file_path) 31 cmd=input(\'please input cmd(q break):\').strip().lower().split() 32 if cmd[0]==\'q\':break 33 cmd=[cmd[1], cmd[5:]] 34 if \'\\\'\'in cmd[1][2]:cmd[1][2]=cmd[1][2].strip(\'\\\'\') 35 if \'\\"\'in cmd[1][2]:cmd[1][2]=cmd[1][2].strip(\'\\"\') 36 for line in staff_table: 37 if cmd[1][1] in [\'>\',\'<\',\'>=\',\'<=\']: 38 if (cmd[1][1]==\'>\'and int(line[cmd[1][0]]) > int(cmd[1][2])) or (cmd[1][1]==\'>=\'and int(line[cmd[1][0]]) >= int(cmd[1][2])) or (cmd[1][1]==\'<\'and int(line[cmd[1][0]]) < int(cmd[1][2])) or (cmd[1][1]==\'<=\'and int(line[cmd[1][0]]) <= int(cmd[1][2])): 39 output(line, cmd) 40 n += 1 41 elif cmd[1][1] == \'=\'and (line[cmd[1][0]] in [cmd[1][2] ,cmd[1][2].strip(\'\\\'\'),cmd[1][2].strip(\'\\"\'),cmd[1][2].lower()] or (cmd[1][2].isdigit() and line[cmd[1][0]] == int(cmd[1][2]))): 42 output(line,cmd) 43 n += 1 44 elif cmd[1][1] == \'like\' and cmd[1][2] in line[cmd[1][0]].split(\'-\') or cmd[1][2] in line[cmd[1][0]] or cmd[1][2] in line[cmd[1][0]].lower(): 45 output(line,cmd) 46 n += 1 47 print(\'相关查询共%d条\' % n) 48 log.info(\'select %s %s %s\'%(cmd[1],cmd[0],n)) 49 def create(): #创建 只判断年龄、手机号格式,入职时间为当前时间 50 phone=[] 51 file_to_date(file_path) 52 while True: 53 info=input(\'Please enter your name,age,phone number and dept\\nuse \\\',\\\' to separate(q for break):\').strip().split(\',\') 54 if info[0]==\'q\':break 55 info={\'staff_id\':len(staff_table)+1,\'name\':info[0].strip(),\'age\':info[1].strip(),\'phone\':info[2].strip(),\'dept\':info[3].strip(),\'enroll_date\':time.strftime(\'%Y-%m-%d\', time.localtime()) } 56 if not info[\'age\'].isdigit() or int(info[\'age\'])not in range(1,110): 57 print(\'Incorrect age format\') 58 continue 59 for line in staff_table: 60 phone.append(line[\'phone\']) 61 if info[\'phone\'] in phone: 62 print(\'The phone number already exists\') 63 continue 64 if len(info[\'phone\'])!=11 or not info[\'phone\'].isdigit() or not info[\'phone\'].startswith(\'1\'): 65 print(\'Incorrect phone number format\') 66 continue 67 if not info[\'age\'].isdigit() or int(info[\'age\'])not in range(1,110): 68 print(\'Incorrect age format\') 69 continue 70 staff_table.append(info) 71 log.info(\'create %s\'%info) 72 print(\'Create user success\') 73 date_to_file(file_path) 74 def delete(): #删除 75 while True: 76 print_table(file_path) 77 cmd_n=int(input(\'Please enter the number to delete(0 for break):\')) 78 if cmd_n==0:break 79 if cmd_n-1 not in range(0,len(staff_table)): 80 print(\'Beyond the optional range\') 81 continue 82 log.info(\'delete %s\'%staff_table[cmd_n-1]) 83 staff_table.pop(cmd_n-1) 84 for i,line in enumerate(staff_table,1): 85 line[\'staff_id\']=i 86 date_to_file(file_path) 87 def update(): #更新 可去除单引号、双引号 88 global staff_table 89 while True: 90 print_table(file_path) 91 print(\'Syntax examples:\\n UPDATE staff_table SET dept=\\\'Market\\\' WHERE where dept=\\\'IT\\\' \') 92 cmd = input(\'Please enter the modified information(q for break):\\n\').split() 93 if cmd[0]==\'q\':break 94 cmd=[cmd[3],cmd[6]] 95 sort=cmd[0].split(\'=\')[0] 96 where=cmd[1].split(\'=\')[0] 97 after = cmd[0].split(\'=\')[1] 98 before = cmd[1].split(\'=\')[1] 99 if \'\\"\' in cmd[0] or \'\\"\' in cmd[1]: 100 after = cmd[0].split(\'=\')[1].strip(\'\\"\') 101 before = cmd[1].split(\'=\')[1].strip(\'\\"\') 102 if \'\\\'\'in cmd[0] or \'\\\'\'in cmd[1]: 103 after=cmd[0].split(\'=\')[1].strip(\'\\\'\') 104 before=cmd[1].split(\'=\')[1].strip(\'\\\'\') 105 for line in staff_table: 106 if line[where]== before: 107 log.info(\'update where %s=%s :%s %s--->%s\' % (where, before, sort,line[sort],after)) 108 line[sort]= after 109 date_to_file(file_path) 110 def main(): 111 while True: 112 print(\'The function menu:1、select 2、create 3、delete 4、update 5、view all(\\\'q\\\' for break)\') 113 cmd=input(\'please input the cmd:\').strip() 114 if cmd == \'1\':select() 115 elif cmd == \'2\':create() 116 elif cmd == \'3\':delete() 117 elif cmd == \'4\':update() 118 elif cmd == \'5\':print_table(file_path) 119 elif cmd == \'q\':break 120 else:continue 121 main()
1 2017-06-23 10:43:59,986-root 2 INFO:select [\'age\', \'>\', \'22\'] 3 3 2017-06-23 10:45:06,985-root 4 INFO:select [\'dept\', \'=\', \'it\'] * 1 5 2017-06-23 10:48:08,377-root 6 INFO:create {\'staff_id\': 5, \'name\': \'ogen\', \'age\': \'18\', \'phone\': \'12345678901\', \'dept\': \'IT\', \'enroll_date\': \'2017-06-23\'} 7 2017-06-23 10:57:42,161-root 8 INFO:delete {\'staff_id\': 5, \'name\': \'ogen\', \'age\': \'18\', \'phone\': \'12345678901\', \'dept\': \'IT\', \'enroll_date\': \'2017-06-23\'} 9 2017-06-23 12:01:01,152-root 10 INFO:update where dept=Market :dept Market--->IT
2、根据用户输入选择可以完成以下功能:
(1)创建文件,如果路径不存在,创建文件夹后创建文件
(2)查看当前路径
(3)在当前目录及所有子目录下查找文件名包含特定字符串的文件,比如查找所有txt文件
1 import os 2 def create_file(): 3 while True: 4 file_path=input(\'Please input file path:\').strip() 5 if file_path==\'q\':break 6 if os.path.exists(file_path): 7 print(\'File already exists\') 8 else: 9 file_dir=os.sep.join(file_path.split(os.sep)[:-1]) 10 os.makedirs(file_dir) 11 f=open(file_path,\'w\') 12 f.close() 13 def find_file(): 14 while True: 15 cmd=input(\'Please input the file you want to find:\').strip() 16 if cmd==\'q\':break 17 for dir,_,files in os.walk(os.getcwd()): 18 for file in files: 19 file_name=\'%s%s%s\'%(dir,os.sep,file) 20 if cmd in file: 21 print(file_name) 22 def main(): 23 while True: 24 print(\'The function menu:1、Create file 2、The current path 3、Find file\') 25 cmd=input(\'>>>:\').strip() 26 if cmd == \'q\':break 27 elif cmd==\'1\':create_file() 28 elif cmd==\'2\':print(os.getcwd()) 29 elif cmd==\'3\':find_file() 30 else:continue 31 main()
以上是关于文件增删改查(加日志记录)有关文件小程序的主要内容,如果未能解决你的问题,请参考以下文章