python从包含全班同学信息的.csv格式文件中读入数据,根据用户输入的分组要求进行随机分组,显示分组结果并将其写入.csv格式文件中代码
时间: 2024-05-14 20:18:54 浏览: 67
用python读取CSV数据
首先需要导入csv和random模块:
```python
import csv
import random
```
然后读入包含全班同学信息的.csv文件,假设该文件包含两列数据,第一列为学生姓名,第二列为学生学号:
```python
with open('students.csv', 'r') as f:
reader = csv.reader(f)
students = [(row[0], row[1]) for row in reader]
```
接下来,根据用户输入的分组要求,将学生列表随机分组,假设要求将全班分为3组:
```python
group_size = len(students) // 3
random.shuffle(students)
groups = [students[i:i+group_size] for i in range(0, len(students), group_size)]
```
最后,将分组结果显示出来并将其写入.csv文件中:
```python
with open('groups.csv', 'w', newline='') as f:
writer = csv.writer(f)
for i, group in enumerate(groups):
print('Group {}:'.format(i+1))
for student in group:
print(student[0])
writer.writerow([i+1, student[0], student[1]])
```
完整代码:
```python
import csv
import random
with open('students.csv', 'r') as f:
reader = csv.reader(f)
students = [(row[0], row[1]) for row in reader]
group_size = len(students) // 3
random.shuffle(students)
groups = [students[i:i+group_size] for i in range(0, len(students), group_size)]
with open('groups.csv', 'w', newline='') as f:
writer = csv.writer(f)
for i, group in enumerate(groups):
print('Group {}:'.format(i+1))
for student in group:
print(student[0])
writer.writerow([i+1, student[0], student[1]])
```
阅读全文