Python练习,还有一些不足之处,望指教。
from faker import Faker
import xlrd
import xlwt
import pandas as pd
import datetime
fake = Faker('zh_CN')
start_date = datetime.date(year=2000,month=1,day=1)
end_date = datetime.date(year=2020,month=1,day=1)
#m=id_card//1000
#n=m%100000000
def save_to_excel():
work_book = xlwt.Workbook(encoding='gbk')
work_sheet = work_book.add_sheet('student')
# 添加字段名
head = ['姓名',
'身份证号',
'性别',
'出生日期',
'省份',
'家庭地址',
'职业',
'入职日期',
'手机号',
'邮箱',
'信用卡号']
for h in range(len(head)):
work_sheet.write(0, h, head[h])
# 添加构造的随机数据
for i in range(1000):
name = fake.name()#姓名
id_card = fake.ssn()#身份证号
#sex=
birth = fake.date_object() #出生日期
shengfen = fake.province()#省份
ip_address = fake.address()#家庭住址
j_ob = fake.job()#职业
job_time = fake.date_between(start_date=start_date,end_date=end_date)
phone = fake.phone_number()#电话号码
e_mail = fake.email()#电子邮件
c_redit_card_number = fake.credit_card_number()#信用卡号
work_sheet.write(i+1, 0, name)
work_sheet.write(i+1, 1,id_card)
#work_sheet.write(i+1, 2,sex)
work_sheet.write(i+1, 3,birth)
work_sheet.write(i+1, 4, shengfen)
work_sheet.write(i+1, 5, ip_address)
work_sheet.write(i+1, 6, j_ob)
work_sheet.write(i+1, 7, job_time)
work_sheet.write(i+1, 8, phone)
work_sheet.write(i+1, 9, e_mail)
work_sheet.write(i+1, 10, c_redit_card_number)
work_book.save('student.xls')
def save_to_excel2(file_path, n):
res = []
for i in range(n):
res.append([fake.name(),
fake.ssn(),
fake.date_object(),
fake.province(),
fake.address(),
fake.job(),
fake.date_between(start_date=start_date,end_date=end_date),
fake.phone_number(),
fake.email(),
fake.credit_card_number(),])
# list转dataFrame
df = pd.DataFrame(data=res, columns=['姓名',
'身份证号',
'性别',
'出生日期',
'省份',
'家庭地址',
'职业',
'入职日期',
'手机号',
'邮箱',
'信用卡号',
])
# 保存到本地excel
df.to_excel(file_path, index=False)
if __name__ == '__main__':
save_to_excel()
df = pd.read_excel('student.xls')#, sheetname='Sheet1', header=None) # 使用pandas模块读取数据
print('开始写入txt文件...')
df.to_csv('student.txt', header=None, sep=',', index=False) # 写入,逗号分隔
print('文件写入成功!')