用faker和pandas库生成测试数据【杭州多测师】【杭州多测师_王sir】

from faker import Faker
import csv
import pandas as pd
# from urllib import parse
class Create_Data(object):
    
    def __init__(self):
        # 选择中文
        fake = Faker('zh_CN')
        # 生成数据改变循环体来控制数据量rang(?)
        self.data_total = [
            [fake.name(), fake.job(), fake.company(), fake.phone_number(), fake.company_email(), fake.address(),
             fake.date_time(tzinfo=None)] for x in range(5)]
        print(self.data_total)

    # 写入excel
    # def deal_excel(self):
    #     df = pd.DataFrame(self.data_total,
    #                       columns=['name', 'job', 'company', 'phone_number', 'company_email', 'address', 'date_time'])
    #     # 保存到本地excel
    #     df.to_excel("data_total.xlsx", index=False)
    #     print("Processing completed to excel")

    # 写入txt
    def deal_txt(self):
        with open('data_total.txt', 'w', errors='ignore', encoding='utf-8') as output:
            # output.write('name,job,company,phone_number.company_email.address.date_time\n')
            for row in self.data_total:
                rowtxt = '{},{},{},{},{}'.format(row[0], row[1], row[2], row[3],row[4])
                # print(rowtxt)
                output.write(rowtxt.strip(" "))
                # output.write('\n')
            output.close()
        print("Processing completed to txt")
    # 写入 csv
    def deal_csv(self):
        with open("data_toral.csv",'w',encoding='utf-8') as output:
            csv_writer = csv.writer(output)
            for row in self.data_total:
                csv_writer.writerow(row)
            output.close()
        # f = open("data_toral.csv",'w',encoding='utf-8')
        # csv_writer = csv.writer(f)
        # for i in self.data_total:
        #     csv_writer.writerow(i)


    def write_raw_index(self,filename):
        '''
        """在csv文件中第一行添加索引字段"""
        :return:
        '''
        with open(filename, 'r+', encoding='utf-8') as f:
            content = f.read()
            f.seek(0, 0)
            text = 'name'+ ','+'job'+ ',' + 'company'+ ',' + 'phone_number'+ ',' + 'company_email'+ ',' + 'address'+',' + 'date_time'
            f.write(text + '\n' + content)


if __name__ == '__main__':
    cd = Create_Data()
    cd.deal_txt()
    cd.deal_csv()
    f = "D:\project\hangzhou\dcs15\lesson\data_toral.csv"
    cd.write_raw_index(f)

 

 

posted @ 2022-06-07 17:59  多测师_树哥  阅读(55)  评论(0编辑  收藏  举报