- Follow below steps to write data into a CSV file using Python
- open the CSV file(example.csv) for writing (w mode) by using the open() function.
- create a CSV writer object by calling the writer() function.
- write data to CSV file by calling the writerow() / writerows()
writerow(): This method writes a single row at a time.
# writerow() Example
import csv
with open("emps.csv", "w", newline="") as f:
data = csv.writer(f)
header = ["eno", "ename", "emarks"]
data.writerow(header)
n = int(input("enter total emp's:"))
for x in range(n):
eno = input("enter eno:")
ename = input("enter ename:")
emarks = input("enter esal:")
data.writerow([eno, ename, emarks])
print("successfully store the data")
writerows(): This method is used to write multiple rows at a time.
# writerows() Example
import csv
with open("emps.csv", "w", newline="") as f:
data = csv.writer(f)
header = ["eno", "ename", "emarks"]
data.writerow(header)
n = int(input("enter total emp's:"))
final_data = []
for x in range(n):
eno = input("enter eno:")
ename = input("enter ename:")
emarks = input("enter esal:")
final_data.append([eno,ename,emarks])
data.writerows(final_data)
print("successfully store the data")