Rohit
Rohit

Reputation: 858

How to write data into a CSV file using python?

I'm wrinting trying to write the following data into a csv file.The data is employdetails

name1-surname1-place1

name2-surname2-place2

name3-surname3-place3

name4-surname4-place4

I want the output to be on CSV files one below the other on separate rows.

I have written the below code

reader = csv.reader(file)

op = open(path+"op.CSV", "wb")

String=list[0] + "-" + list[1] + "-" + list[2] + "-" + list[4]

 op.writer(String)

PLEASE HELP.

Thanks in advance.

-KD

Upvotes: 0

Views: 3090

Answers (1)

xecgr
xecgr

Reputation: 5193

If i've understood your question well, you are looking for this:

>>> import csv
>>> employees = [
...     'name1-surname1-place1',
...     'name2-surname2-place2',
...     'name3-surname3-place3',
...     'name4-surname4-place4',
... ]
>>> with open('out.csv', 'w') as out:
...     writer = csv.writer(out)
...     for e in employees:
...         writer.writerow(e.split("-"))
... 
>>> 
>>> 
host:~$ head out.csv 
name1,surname1,place1
name2,surname2,place2
name3,surname3,place3
name4,surname4,place4

Upvotes: 2

Related Questions