Create random data to csv file using Python

Photo by Christina Morillo from Pexels

Today We will create random data to csv file like this

prerequisite

  • python3

first, make sure you use python3, when you have checked your python version then, you have to install faker

pip install Faker

create random-person.py and insert the following code.

import sys
import csv
from faker import Faker
fake = Faker()
number_of_records = int(sys.argv[1])
with open('random-person.csv', mode='w') as file:
file_writer = csv.writer(file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
file_writer.writerow(['first_name', 'last_name', 'age'])
for _ in range(number_of_records):
file_writer.writerow([fake.first_name(), fake.last_name(), fake.numerify("@#")])

open terminal and run command to execute the file

python random-person.py 10

open random-person.csv, you will see these output

first_name,last_name,age
Larry,Brown,75
Andrew,Maynard,3
Samantha,Neal,6
Crystal,Levy,95
Regina,Whitehead,46
James,Rowe,5
Brian,Harper,5
Christopher,Martin,14
Deborah,Wilson,7
James,Miller,96

now, I will explain the python code

import sys
import csv
from faker import Faker
fake = Faker()
number_of_records = int(sys.argv[1])
with open('random-person.csv', mode='w') as file:
file_writer = csv.writer(file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
file_writer.writerow(['first_name', 'last_name', 'age'])
for _ in range(number_of_records):
file_writer.writerow([fake.first_name(), fake.last_name(), fake.numerify("@#")])
on line 5: fake = Faker()

use faker to generate random data

on line 6: number_of_records = int(sys.argv[1])

read argument value from “python random-person.py 10″ we get value 10 on this line

on line 8: with open(‘random-person.csv’, mode=’w’) as file:

open csv file with write mode

on line 9: file_writer = file_writer = csv.writer(file)

define csv operator

on line 11: file_writer.writerow([‘first_name’, ‘last_name’, ‘age’])

write header

on line 14: file_writer.writerow([fake.first_name(), fake.last_name(), fake.numerify(“@#”)])

write generate data (you can see list data can fake on standard provider)

fake.numerify(“@#”)

fake number by the following

@ : are replaced with a random non-zero digit or an empty string

# : are replaced with a random digit (0 to 9)

now, you can create random data to csv file easily. thank you for reading & enjoy your coding 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s