简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM