def show(self): if os.path.exists(self.filename): with open(self.filename, 'r') as rfile: reader=csv.reader(rfile) #读取csv文件 student_information=[] #将结果转换为列表 if student_information != []: self.formet.output(student_information) #调用格式化的展示函数 else: print('暂未保存学生信息')
时间: 2024-02-14 19:06:11 浏览: 26
这段代码中,`show` 方法主要实现的功能是读取 CSV 文件中的学生信息,并将其转化为列表 `student_information`,最后调用 `output` 方法展示学生信息。如果 CSV 文件不存在,则打印提示信息。
其中,`with open(self.filename, 'r') as rfile:` 可以自动关闭文件,防止文件泄露。
需要注意的是,代码中的 `student_information=[]` 是在 `if` 语句中,这意味着 `if` 语句的条件永远为 `False`,因此 `student_information` 列表永远为空。如果想要将 CSV 文件中的学生信息保存到 `student_information` 列表中,应该将 `student_information=[]` 放在 `with` 语句块内,如下所示:
```python
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('暂未保存学生信息')
```
这样,`show` 方法就可以正确地读取 CSV 文件中的学生信息,并将其保存到 `student_information` 列表中。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)