Write to a CSV file

Asked

Viewed 4,852 times

6

I need my script write to a CSV file. It 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 day and time column. However, you are experiencing error while trying to write to the file (writer.writerows(dia,hora)); displays error message :

Typeerror: writerows() takes Exactly 2 Arguments (3 Given)

Follows 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'), '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()
  • After change to: Writer.writerows([dia,hora]) displays the following message : Traceback (Most recent call last): File "C: Test.py", line 25, in <module> Writer.writerows([dia,hora]) File "C: Python27 lib csv.py", line 157, in writerows Rows.append(self. _dict_to_list(rowdict)) File "C: Python27 lib csv.py", line 148, in _dict_to_list + ", ". Join([Repr(x) for x in wrong_fields]) Valueerror: Dict contains Fields not in fieldnames: '1', '9'

  • Edit your question and add a fragment (the first 10 lines, for example) of the csv file you have to read, and the last error message that is occurring.

1 answer

3

In writer.writerows([dia,hora]) Voce is trying to record a list and csv.DictWriter expects a dictionary. Without knowing the contents of your input file, I made a notification of your code and managed the teste2.csv according to what Voce specified. 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 creation date/time, and the two information is separated by a space, as would be the conversion of timestamp for string python. The code below will read from this file and write to teste2.csv, but with 2 headers, one for the day and another for the time.

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

Upshot

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
  • Hello, changing to Writer.writerow({'day': day, 'time': hour}) same executed correctly. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.