user4815708
user4815708

Reputation:

Python - for loop to write across a row in CSV

Basically, I have some code that asks a user to input a comma-separated list of currencies and 2 dates. I want to take these currencies, and write it to a CSV file in the following format:

Date, Curr1, Curr2, Curr3, ... , Currn
---, x, x, x, ..., n
---, x, x, x, ..., n

Where x is the exchange rate for the currency on the given date. I have tried using csv.writer like this:

    writer = ex.csv.writer(f, delimiter=',')
    writer.writerow(['Date', codes]) 
    for i in range(delta.days + 1):
        date = real_date + ex.timedelta(days=i)
        rates = exchrates(date) #function fetches all rates on given date, returns dict
        for j in codes:
            writer.writerow([date, rates[j.upper()]])

but it doesn't write to the file how I would like, rather like this:

Date,['RSD', 'GBP']
2008-04-11,51.586749
2008-04-11,0.506908
2008-04-12,51.586749
2008-04-12,0.506674

putting each currency's value on a new row, whereas I want it like:

Date,RSD,GBP
2008-04-11,51.586749,0.506908
2008-04-12,51.586749,0.506674

I am a beginner to Python so apologies if this is trivial. Any help would be greatly appreciated.

Thanks.

Upvotes: 0

Views: 165

Answers (3)

tynn
tynn

Reputation: 39843

Well. The output is just, what you actually programmed it to be.

With writer.writerow() you should write only a list of data. Try this:

writer = ex.csv.writer(f, delimiter=',')
writer.writerow(['Date'] + codes) # codes seems to be a list, so just append it
for i in range(delta.days + 1):
    date = real_date + ex.timedelta(days=i)
    rates = exchrates(date)
    writer.writerow([date] + [rates[j.upper()] for j in codes]) # only one line

Upvotes: 0

chepner
chepner

Reputation: 531075

writerow writes just that: an entire row. You need to build the row using codes and make one call.

for i in range(delta.days + 1):
    date = real_date + ex.timedelta(days=i)
    rates = exchrates(date) #function fetches all rates on given date, returns dict
    writer.writerow([date] + [rates[j.upper()] for j in codes])

Upvotes: 0

Georgi Dimitrov
Georgi Dimitrov

Reputation: 173

You're writing the exchange rate for each currency on a new line because in the inner for cycle you're iterating through the list ot codes and you're performing a write operation for each code. Instead of

for j in codes:
    writer.writerow([date, rates[j.upper()]])

you should do something like this:

new_row = [date]
for j in codes:
    new_row.append(rates[j.upper()])
writer.writerow(new_row)

Upvotes: 1

Related Questions