[python]代码库
import random
import csv
# 生成随机csv表文件,做实验用
def gen_csv(filename):
# csv文件数据
datas = []
# csv文件表头
data_header = ['组名']
# 每一组最多可以有10个组员
for i in range(10):
data_header.append('组员'+str(i))
# 先加表头
datas.append(data_header)
# 有10行数据
for i in range(10):
# 这一行数据
row_data = []
row_data.append('组'+str(i))
# 组员数量随机
for j in range(random.randint(3, 10)):
# 组员名称随机
row_data.append(str(random.randint(0, 1000)))
# 向表中添加数据行
datas.append(row_data)
print('您生成了数据')
print(datas)
# 写出csv文件
with open(filename, 'w', newline='') as f:
writer = csv.writer(f)
for row in datas:
writer.writerow(row)
print('生成模拟表')
# 将组信息csv文件转换为2列状的csv文件
def from_csv_to_2col_csv(filename):
# 读入csv文件转换出组信息列表
with open(filename) as f:
reader = csv.reader(f)
groups = list(reader)
# 对每一行组信息数据进行操作
new_datas = [['组名', '组员']]
# 遍历每一组
for group in groups[1:]:
# 遍历每个成员
for member in group[1:]:
# 组成对应关系
new_row_data = []
new_row_data.append(group[0])
new_row_data.append(member)
new_datas.append(new_row_data)
print('转换来的数据')
print(new_datas)
with open('new_groups.csv', 'w', newline='') as f:
writer = csv.writer(f)
for row in new_datas:
writer.writerow(row)
print('生成目标表')
if __name__ == '__main__':
filename = 'groups.csv'
gen_csv(filename)
from_csv_to_2col_csv(filename)