Write to a CSV file

6

I need my script to write to a CSV file. The same will open a CSV file that has the column created_at (date and time), after that, the variable will be "broken" and will be written in a new CSV file the column day and time. However, it is displaying an error when trying to write to the file ( writer.writerows(dia,hora) ); Error Message:

  

TypeError: writerows () takes exactly 2 arguments (3 given)

Follow the code below:

import csv
import re
import os

fin = open('teste.csv', 'r')

fout = open('teste2.csv', 'w')

reader = csv.DictReader(fin, delimiter=',')
writer = csv.DictWriter(fout, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL,fieldnames=reader.fieldnames)

with open(os.path.join('teste2.csv'), 'wb') as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames = ['dia','hora'], delimiter = ',')
    writer.writeheader()



for row in reader:
    data = row['created_at'].split("T")[0]
    dia = data.split("-")[2]

    horario = row['created_at'].split("T")[1]
    hora= horario.split(":")[0]

    writer.writerows([dia,hora])  

fin.close() 
fout.close()
    
asked by anonymous 29.04.2017 / 17:18

1 answer

3

In writer.writerows([dia,hora]) you are trying to write a list and csv.DictWriter expects a dictionary. Without knowing the content of your input file, I made an adptación of your code and generated the teste2.csv according to what you specified. For this I created a csv with the following content:

test.csv

created_at
01-02-17 01:55:00
01-02-17 02:55:00
01-03-17 03:00:55
01-04-17 04:55:00

In this file there is only one header for the date / time of the creation, and the two information are separated by a space, as would be the conversion from timestamp to string in python. The code below will read from this file and write to test2.csv , but with 2 headers, one for the day and another for the hour.

Code

import csv
import re
import os

fin = open('teste.csv', 'r')

fout = open('teste2.csv', 'w')

reader = csv.DictReader(fin, delimiter=',')
writer = csv.DictWriter(fout, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL,fieldnames=reader.fieldnames)

with open(os.path.join('teste2.csv'), 'w') as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames = ['dia','hora'], delimiter = ',')
    writer.writeheader()

    for row in reader:
        list_dh = row['created_at'].split(' ')
        dh = dict(dia=list_dh[0], hora=list_dh[1])
        writer.writerow(dh)    

fin.close() 
fout.close()

Result

dia,hora
01-02-17,01:55:00
01-02-17,02:55:00
01-03-17,03:00:55
01-04-17,04:55:00
    
30.04.2017 / 01:30