def search(): student_query = [] while True: id = "" name = "" if os.path.exists(filename): mode = input('按ID查找请输入1,按姓名查找请输入2') if mode == '1': id = input("请输入学生id:") elif mode == '2': name = input("请输入学生姓名:") else: print("您的输入有误,请重新输入") search() with open(filename, 'r', encoding='utf-8') as rfile: student = rfile.readlines() for item in student: d = dict(eval(item)) if id != '': if d['id'] == id: student_query.append(d) elif name != '': if d['name'] == name: student_query.append(d) # 显示查询结果 show_student(student_query) # 清空列表 student_query.clear() answer = input("是否要继续查询y/n\n") if answer == 'y': continue elif answer == 'n': break else: print("暂未保存学生信息!!!")

时间: 2024-02-10 07:24:58 浏览: 32
这段代码是一个查询学生信息的函数。它通过循环让用户选择按照学生ID还是姓名进行查询。然后打开存储学生信息的文件,逐行读取文件内容,并将每行内容转换为字典。根据用户选择的查询方式,将符合条件的学生信息添加到查询结果列表中。最后显示查询结果,清空查询结果列表,并询问用户是否继续查询。如果回答是,则继续循环,否则退出循环。如果找不到保存学生信息的文件,会显示相应的提示信息。
相关问题

def _has_cache(cache): has_cache = True for value in cache.values(): if not os.path.exists(value): has_cache = False break return has_cache

这段代码定义了一个 `_has_cache` 方法,用于检查缓存中的文件是否存在。下面是对该方法的解释: - `cache` 是一个字典,其中键是缓存项的名称,值是缓存项的路径。 - `has_cache` 是一个布尔变量,初始值为 `True`。 - 在一个循环中,遍历 `cache` 字典中的所有值: - `value` 是当前缓存项的路径。 - `os.path.exists(value)` 检查该路径是否存在。如果不存在,则将 `has_cache` 设置为 `False` 并跳出循环。 - 返回 `has_cache`,表示缓存中的所有文件是否存在。 该方法用于在代码中检查缓存项的文件是否存在。如果某个缓存项的文件不存在,可以根据需要采取相应的处理措施,例如重新生成缓存或从其他位置加载数据。

def search(self): student_query = [] while True: id = '' name = '' if os.path.exists(self.filename): # 判断文件是否存在 mode = input('按id查找请输入1,按姓名查找请输入2\n') if mode == '1': id = input('请输入要查找的id:') elif mode == '2': name = input('请输入要查找的姓名:') else: print('您的输入有误,请重新输入') continue with open(self.filename, 'r') as rfile: allstudent = csv.DictReader(rfile) # 读取csv文件 for item in allstudent: if item['id'] == id or item['姓名'] == name: student_query.append(item) # 查询是否有对应id或姓名的学生,找到之后放到查询结果列表中 # 显示查询结果 self.show_student(student_query) answer = input('是否要继续查询?y/n\n') if answer == 'y' or answer == 'Y': # 清空列表 student_query.clear() continue else: break else: print('暂未保存该学生信息') return # 展示所有学生 def show(self): if os.path.exists(self.filename): with open(self.filename, 'r') as rfile: reader = csv.reader(rfile) # 读取csv文件 student_information = [] # 将结果转换为列表 for row in reader: student_information.append(row) if student_information != []: self.formet.output(student_information) # 调用格式化的展示函数 else: print('暂未保存学生信息')请你帮我修正错误

这段代码中似乎没有明显的错误,但是可以做一些改进和优化: 1. 在查询学生信息时,可以使用 `input` 函数的参数来限制用户输入的值,而不是用 `continue` 语句来强制用户重新输入。例如: ``` mode = input('按id查找请输入1,按姓名查找请输入2\n[1/2]: ') while mode not in ['1', '2']: print('您的输入有误,请重新输入') mode = input('按id查找请输入1,按姓名查找请输入2\n[1/2]: ') ``` 2. 在读取 CSV 文件时,可以使用 `csv.DictReader` 函数来读取,这样可以直接将每行数据转换为字典格式,方便查询和处理。 3. 在展示学生信息时,可以使用 `csv.reader` 函数的 `DictReader` 类来读取,这样可以直接将每行数据转换为字典格式,方便展示和处理。 4. 可以添加一些异常处理机制,例如文件不存在或者读取错误时,给出提示和处理方法。 下面是修改后的代码: ``` import csv import os class Student: def __init__(self, filename, formet): self.filename = filename self.formet = formet def search(self): student_query = [] while True: id = '' name = '' if not os.path.exists(self.filename): print('暂未保存该学生信息') return mode = input('按id查找请输入1,按姓名查找请输入2\n[1/2]: ') while mode not in ['1', '2']: print('您的输入有误,请重新输入') mode = input('按id查找请输入1,按姓名查找请输入2\n[1/2]: ') if mode == '1': id = input('请输入要查找的id:') elif mode == '2': name = input('请输入要查找的姓名:') with open(self.filename, 'r') as rfile: allstudent = csv.DictReader(rfile) for item in allstudent: if item['id'] == id or item['姓名'] == name: student_query.append(item) if student_query: self.show_student(student_query) else: print('未找到符合条件的学生信息') answer = input('是否要继续查询?[y/n]: ') if answer.lower() != 'y': break student_query.clear() def show(self): if not os.path.exists(self.filename): print('暂未保存学生信息') return with open(self.filename, 'r') as rfile: reader = csv.DictReader(rfile) student_information = [] for row in reader: student_information.append(row) if student_information: self.formet.output(student_information) else: print('暂未保存学生信息') def show_student(self, students): headers = ['id', '姓名', '性别', '年龄', '成绩'] student_information = [headers] for student in students: row = [student[h] for h in headers] student_information.append(row) self.formet.output(student_information) class Formet: def output(self, student_information): for row in student_information: print('\t'.join(row)) filename = 'students.csv' student = Student(filename, Formet()) student.search() ```

相关推荐

将下面代码简洁化:def split_dataset(img_path, target_folder_path, output_path): filename = [] total_imgs = os.listdir(img_path) #for root, dirs, files in os.walk(img_path): for img in total_imgs: filename.append(img) np.random.shuffle(filename) train = filename[:int(len(filename) * 0.9)] test = filename[int(len(filename) * 0.9):] out_images = os.path.join(output_path, 'imgs') if not os.path.exists(out_images): os.makedirs(out_images) out_images_train = os.path.join(out_images, 'training') if not os.path.exists(out_images_train): os.makedirs(out_images_train) out_images_test = os.path.join(out_images, 'test') if not os.path.exists(out_images_test): os.makedirs(out_images_test) out_annotations = os.path.join(output_path, 'annotations') if not os.path.exists(out_annotations): os.makedirs(out_annotations) out_annotations_train = os.path.join(out_annotations, 'training') if not os.path.exists(out_annotations_train): os.makedirs(out_annotations_train) out_annotations_test = os.path.join(out_annotations, 'test') if not os.path.exists(out_annotations_test): os.makedirs(out_annotations_test) for i in train: print(os.path.join(img_path, i)) print(os.path.join(out_images_train, i)) shutil.copyfile(os.path.join(img_path, i), os.path.join(out_images_train, i)) annotations_name = "gt_" + i[:-3] + 'txt' shutil.copyfile(os.path.join(target_folder_path, annotations_name), os.path.join(out_annotations_train, annotations_name)) for i in test: shutil.copyfile(os.path.join(img_path, i), os.path.join(out_images_test, i)) annotations_name = "gt_" + i[:-3] + 'txt' shutil.copyfile(os.path.join(target_folder_path, annotations_name), os.path.join(out_annotations_test, annotations_name))

优化代码 def fault_classification_wrapper(vin, main_path, data_path, log_path, done_path): start_time = time.time() isc_path = os.path.join(done_path, vin, 'isc_cal_result', f'{vin}_report.xlsx') if not os.path.exists(isc_path): print('No isc detection input!') else: isc_input = isc_produce_alarm(isc_path, vin) ica_path = os.path.join(done_path, vin, 'ica_cal_result', f'ica_detection_alarm_{vin}.csv') if not os.path.exists(ica_path): print('No ica detection input!') else: ica_input = ica_produce_alarm(ica_path) soh_path = os.path.join(done_path, vin, 'SOH_cal_result', f'{vin}_sohAno.csv') if not os.path.exists(soh_path): print('No soh detection input!') else: soh_input = soh_produce_alarm(soh_path, vin) alarm_df = pd.concat([isc_input, ica_input, soh_input]) alarm_df.reset_index(drop=True, inplace=True) alarm_df['alarm_cell'] = alarm_df['alarm_cell'].apply(lambda _: str(_)) print(vin) module = AutoAnalysisMain(alarm_df, main_path, data_path, done_path) module.analysis_process() flags = os.O_WRONLY | os.O_CREAT modes = stat.S_IWUSR | stat.S_IRUSR with os.fdopen(os.open(os.path.join(log_path, 'log.txt'), flags, modes), 'w') as txt_file: for k, v in module.output.items(): txt_file.write(k + ':' + str(v)) txt_file.write('\n') for x, y in module.output_sub.items(): txt_file.write(x + ':' + str(y)) txt_file.write('\n\n') fc_result_path = os.path.join(done_path, vin, 'fc_result') if not os.path.exists(fc_result_path): os.makedirs(fc_result_path) pd.DataFrame(module.output).to_csv( os.path.join(fc_result_path, 'main_structure.csv')) df2 = pd.DataFrame() for subs in module.output_sub.keys(): sub_s = pd.Series(module.output_sub[subs]) df2 = df2.append(sub_s, ignore_index=True) df2.to_csv(os.path.join(fc_result_path, 'sub_structure.csv')) end_time = time.time() print("time cost of fault classification:", float(end_time - start_time) * 1000.0, "ms") return

最新推荐

recommend-type

华为OD机试D卷 - 用连续自然数之和来表达整数 - 免费看解析和代码.html

私信博主免费获取真题解析以及代码
recommend-type

Screenshot_2024-05-10-20-21-01-857_com.chaoxing.mobile.jpg

Screenshot_2024-05-10-20-21-01-857_com.chaoxing.mobile.jpg
recommend-type

数字图像处理|Matlab-频域增强实验-彩色图像的频域滤波.zip

数字图像处理|Matlab-频域增强实验-彩色图像的频域滤波.zip
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

spring添加xml配置文件

1. 创建一个新的Spring配置文件,例如"applicationContext.xml"。 2. 在文件头部添加XML命名空间和schema定义,如下所示: ``` <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。
recommend-type

"互动学习:行动中的多样性与论文攻读经历"

多样性她- 事实上SCI NCES你的时间表ECOLEDO C Tora SC和NCESPOUR l’Ingén学习互动,互动学习以行动为中心的强化学习学会互动,互动学习,以行动为中心的强化学习计算机科学博士论文于2021年9月28日在Villeneuve d'Asq公开支持马修·瑟林评审团主席法布里斯·勒菲弗尔阿维尼翁大学教授论文指导奥利维尔·皮耶昆谷歌研究教授:智囊团论文联合主任菲利普·普雷教授,大学。里尔/CRISTAL/因里亚报告员奥利维耶·西格德索邦大学报告员卢多维奇·德诺耶教授,Facebook /索邦大学审查员越南圣迈IMT Atlantic高级讲师邀请弗洛里安·斯特鲁布博士,Deepmind对于那些及时看到自己错误的人...3谢谢你首先,我要感谢我的两位博士生导师Olivier和Philippe。奥利维尔,"站在巨人的肩膀上"这句话对你来说完全有意义了。从科学上讲,你知道在这篇论文的(许多)错误中,你是我可以依
recommend-type

实现实时监控告警系统:Kafka与Grafana整合

![实现实时监控告警系统:Kafka与Grafana整合](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X2pwZy9BVldpY3ladXVDbEZpY1pLWmw2bUVaWXFUcEdLT1VDdkxRSmQxZXB5R1lxaWNlUjA2c0hFek5Qc3FyRktudFF1VDMxQVl3QTRXV2lhSWFRMEFRc0I1cW1ZOGcvNjQw?x-oss-process=image/format,png) # 1.1 Kafka集群架构 Kafka集群由多个称为代理的服务器组成,这