# 实验2
import random
import csv
import os
def unicode():
val = random.randint(0x4e00, 0x9fbf)
return chr(val)
with open('info.csv', 'w', newline='', encoding='utf-8') as f: # encoding指定编码格式,否则写入乱码
head = ['姓名', '性别', '年龄', '成绩'] # 表头
f_csv = csv.writer(f)
f_csv.writerow(head) # 写入表头
for i in range(0, 50): # 循环,写入50次
row = [unicode()+unicode()+unicode(), random.choice(['男', '女']), random.randint(18, 21), random.randint(0, 101)]
f_csv.writerow(row)
if not os.path.exists('./data'):
os.mkdir('./data')
with open('info.csv', 'r', newline='', encoding='utf-8') as f:
f_csv = csv.reader(f)
headers = next(f_csv) # 文件指针下移一格
for row in f_csv: # 读取每行数据
if int(row[3]) < 60: # 判断分数
with open('./data/'+row[0]+'.dat', 'w', newline='', encoding='utf-8') as fn: # 写入文件,写在了当前data目录下
fn.write(str(head)+'\n')
fn.write(str(row)) # 写入文件
print(row) # 控制台显示