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.

-------------Problems Reply------------

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

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)

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

Category:python Views:1 Time:2018-04-16

Related post

  • Get loop count inside a Python FOR loop 2010-07-01

    In a Python for loop that iterates over a list we can write: for item in list: print item and it neatly goes through all the elements in the list. Is there a way to know within the loop how many times I've been looping so far? For instance, I want to

  • How to use more than one condition in Python for loop? 2011-07-27

    How to use more than one condition in Python for loop? for example in java: int[] n={1,2,3,4,6,7}; for(int i=0;i<n.length && i<5 ;i++){ //do sth } How dose the python for loop do this? --------------Solutions------------- The Python for

  • How does Python for loop work? 2009-08-18

    I am used to the C++ way of for loops, but the Python loops have left me confused. for party in feed.entry: print party.location.address.text Here party in feed.entry. What does it signify and how does it actually work? --------------Solutions-------

  • Convert C++ to Python (For Loop multiple assignment) 2010-01-29

    Convert to python: #include <iostream> using namespace std; int main(int argc, char** argv) { for (int i = 0, j = i + 3; i < 100; ++i, j= i+3) cout << i << " j: " << j << endl; getchar(); return 0; } I try: for i in r

  • Python for loop question 2010-03-12

    I was wondering how to achieve the following in python: for( int i = 0; cond...; i++) if cond... i++; //to skip an run-through I tried this with no luck. for i in range(whatever): if cond... : i += 1 --------------Solutions------------- Python's for

  • Scoping in Python 'for' loops 2010-08-31

    I'm not asking about Python's scoping rules; I understand generally how scoping works in Python for loops. My question is why the design decisions were made in this way. For example (no pun intended): for foo in xrange(10): bar = 2 print(foo, bar) Th

  • Java or Groovy equivalent of python for loop + izip 2010-09-13

    Does anyone know the java or groovy equivalent of a python for loop using izip? python example: for item_one, item_two in izip(list_one, list_two): I'd like to do the same in java or groovy Thanks --------------Solutions------------- I don't think gr

  • Python for-loop look-ahead 2010-11-16

    I have a python for loop, in which I need to look ahead one item to see if an action needs to be performed before processing. for line in file: if the start of the next line == "0": perform pre-processing ... continue with normal processing ... Is th

  • Python: for loop between if-else, how/why does this work? 2011-08-11

    I'm currently going through the Lynda Python tutorial and in the section on generators I see the following code: def isprime(n): if n == 1: return False for x in range(2, n): if n % x == 0: return False else: return True I didn't catch it at first, b

  • HELP: How to have a For loop without hardcoding the end row number 2014-11-11

    How to have a For loop without hardcoding the end row number. For eg: in For i = 1 to 10. I dont want to hardcode that 10 in the for loop. Is there a way to identify the last row with data and make it work that way? something like: For i = 1 to lastR

  • Accessing the index in Python for loops 2009-02-06

    Does anyone know how to access the index itself for a list like this: ints = [8, 23, 45, 12, 78] When I loop through it using a for loop, how do I access the loop index, from 1 to 5 in this case? --------------Solutions------------- Using additional

  • Optimizing python for loops 2010-11-12

    Here are two programs that naively calculate the number of prime numbers <= n. One is in Python and the other is in Java. public class prime{ public static void main(String args[]){ int n = Integer.parseInt(args[0]); int nps = 0; boolean isp; for(

  • Changing colors of a Python for-loop in Vim 2012-01-22

    I've just started learning python and I'm using MacVim as my editor with the Jellybeans color scheme. When I write a for-loop in python the 'for' is colored blue(ish) while the 'in' is not. I see in other themes they are both colored the same. How do

  • error while inserting into mysql from python for loop 2012-01-31

    Possible Duplicate: convert list to string to insert into my sql in one row in python scrapy Is this script correct. I want to insert the scraped out h2,h3,meta data directly into mysql database. The code below does not work correctly. Can someone pl

  • Python for loop issues 2013-03-16

    I'm having issues replicating a for loop in python. Here is my c style script with just the for loop aspects. for ($c=0 ; $c<size($verts); $c++) { //// do some code here $verts = remove($verts[c],$verts); /// remove this item from the $verts list

  • How do I operate on the actual object, not a copy, in a python for loop? 2009-06-12

    let's say I have a list a = [1,2,3] I'd like to increment every item of that list in place. I want to do something as syntactically easy as for item in a: item += 1 but in that example python uses just the value of item, not its actual reference, so

  • Changing variable names with Python for loops 2009-06-29

    I was just wondering if anyone knew of a way to change variable names based off of a for loop for something like this: for i in range(3) group+i=self.getGroup(selected, header+i) so that the names of the variables change to accomodate the data. Thank

  • What is the pythonic way to detect the last element in a python 'for' loop? 2009-10-27

    I'd like to know the best way (more compact and "pythonic" way) to do a special treatment for the last element in a for loop. There is a piece of code that should be called only between elements, being suppressed in the last one. Here is how I curren

  • How to pass value for python for loop? 2009-12-16

    In C/C++: for(int i=0;i<=5;i++) In Python: for i in range(0,5) Question is: s=[1,2,3,4,1] for i in s: for j in s: Here i wanna make second for loop j=1 (j value should be start with 1 like this s[1]=2).How do i pass that value. --------------Solut

  • Python: For loop problem 2010-03-11

    I have a simple for loop problem, when i run the code below it prints out series of 'blue green' sequences then a series of 'green' sequences. I want the output to be; if row[4] is equal to 1 to print blue else print green. for row in rows: for i in

  • in python for loop,, jump over values 2011-03-07

    time=0 gold=0 level=1 for time in range(100): gold+=level if gold>20*level: level+=1 time+=10 with this program gold is added until it reaches a critical amount, then it takes 20s to upgrade a mine so it produces more gold. i'd like to skip those

  • in for loop how to increment the row in data table 2011-05-03

    in for loop how to increment to the next row and add a new member if the if condition is not met. eg. for i ...to ..row.count if condition to compare...if member exists then .... ( not Met ) increment the row in the data table and (goto) else ( add a

  • Python For Loop Slowing With Time 2011-08-21

    So I'm having a little trouble dealing with for loops in Python - as far as I can tell, they're getting slower with time. I'm looping over a range inside of a range, and as time passes, the loop noticeably slows. This is done inside of a game engine,

  • Python: for loop in index assignment 2011-10-14

    While working through the awesome book "Programming Collective Intelligence", by Toby Segaran, I've encountered some techniques in index assignments I'm not entirely familiar with. Take this for example: createkey='_'.join(sorted([str(wi) for wi in w

  • Will the function in python for loop be executed multiple times? 2011-12-03

    Say I have the following class with a method returning a list: Class C(): def f(): return [1,2,3] If I loop over the this method as follows: c=C() for i in c.f(): print i Inside the for loop, will c.f() be executed multiple times? If yes, in order to

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.125 (s). 11 q(s)