How to create random data to csv file using Python

Supakon_k
2 min readFeb 13, 2022

--

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.

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,ageLarry,Brown,75Andrew,Maynard,3Samantha,Neal,6Crystal,Levy,95Regina,Whitehead,46James,Rowe,5Brian,Harper,5Christopher,Martin,14Deborah,Wilson,7James,Miller,96

now, I will explain the python code

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 :)

--

--