標籤:操作 img delete strip() code 簡單操作 pytho update 技術分享
實現對檔案的簡單操作
#!/usr/bin/env python# -*- coding:utf-8 -*-def Find(class_name): class_list = [] tag = False with open(‘data‘, ‘r‘, encoding=‘utf8‘) as f: for line in f: if line.strip() == ‘班級:{0}班‘.format(class_name.strip()): class_list.append(line) tag = True continue if tag and line.find(‘班級:‘) != 0: class_list.append(line) if line.find(‘班級:‘) == 0: tag = False return class_list;def Add(dic): # { ‘班級‘:‘191‘,‘學生‘:[{‘姓名‘:‘張三‘,‘學號‘:‘2018001‘,‘年齡‘:18,‘性別‘:‘男‘},{‘姓名‘:‘李四‘,‘學號‘:‘2018002‘,‘年齡‘:21,‘性別‘:‘男‘},{‘姓名‘:‘小花‘,‘學號‘:‘2018003‘,‘年齡‘:18,‘性別‘:‘女‘},{‘姓名‘:‘小紅‘,‘學號‘:‘2018004‘,‘年齡‘:33,‘性別‘:‘女‘}]} class_obj = eval(dic) class_name = class_obj[‘班級‘] class_list = Find(class_name) if len(class_list) > 0: print(‘系統中已經存在班級[%s]。‘ % (class_name)) return with open(‘data‘, ‘a+‘, encoding=‘utf8‘) as f: f.write(‘\n班級:%s班‘ % (class_name)) for student in class_obj[‘學生‘]: f.write(‘\n 姓名:{0} 學號:{1} 年齡:{2} 性別:{3}‘.format(student[‘姓名‘], student[‘學號‘], student[‘年齡‘], student[‘性別‘])) print(‘添加成功!‘)def Update(dic): class_obj = eval(dic) class_name = class_obj[‘班級‘] class_list = Find(class_name) if len(class_list) == 0: print(‘沒有查詢到該班級資訊。‘) return Delete(class_name) Add(dic) print(‘更新成功!‘)def Delete(class_name): class_list = Find(class_name) if len(class_list) == 0: print(‘沒有查詢到該班級資訊。‘) return class_list = [] tag = False with open(‘data‘, ‘r‘, encoding=‘utf8‘) as old_file: for line in old_file: if line.strip() == ‘班級:{0}班‘.format(class_name.strip()): tag = True continue else: if tag and line.find(‘班級:‘) != 0: continue if line.find(‘班級:‘) == 0: tag = False class_list.append(line) with open(‘data‘, ‘w‘, encoding=‘utf8‘) as new_file: for line in class_list: new_file.write(line) print(‘刪除成功!‘)if __name__ == ‘__main__‘: while True: print(‘\n1、查詢 2、修改 3、添加 4、刪除 ‘) operation = input(‘請輸入操作:‘) if (operation == ‘1‘): class_name = input(‘請輸入查詢的班級名稱:‘) class_list = Find(class_name) if len(class_list) == 0: print(‘沒有查詢到該班級資訊。‘) else: for line in class_list: print(line, end=‘‘) elif (operation == ‘2‘): dic = input(‘請輸入修改的字典資料:‘) Update(dic) elif (operation == ‘3‘): dic = input(‘請輸入添加的字典資料:‘) Add(dic) elif (operation == ‘4‘): class_name = input(‘請輸入刪除的班級名稱:‘) Delete(class_name) else: print("輸入不正確")
班級:191班 姓名:張三 學號:2018001 年齡:18 性別:男 姓名:李四 學號:2018002 年齡:21 性別:男 姓名:小花 學號:2018003 年齡:18 性別:女 姓名:小紅 學號:2018004 年齡:33 性別:女班級:188班 姓名:Oliver 學號:2018005 年齡:18 性別:男 姓名:Alax 學號:2018006 年齡:17 性別:男 姓名:Tom 學號:2018007 年齡:19 性別:男班級:143班 姓名:小白 學號:2018008 年齡:23 性別:男 姓名:小黑 學號:2018009 年齡:22 性別:男 姓名:小藍 學號:2018010 年齡:19 性別:女 姓名:小呂 學號:2018011 年齡:21 性別:男班級:189班 姓名:呂布 學號:2018012 年齡:18 性別:男 姓名:貂蟬 學號:2018013 年齡:17 性別:女 姓名:趙雲 學號:2018014 年齡:17 性別:男 姓名:韓信 學號:2018015 年齡:18 性別:男
data檔案
python 對檔案操作