views:

91

answers:

6

I am trying to print to a file that will look like:

'A'
'1'
'B'
'2'
'C'
'3' 

Given the code below, however, the result is :

['A']
['B']
['C']

This is probably a 'softball' question, but what am I doing wrong here?

l1 = ['1']
l2 = ['A']
l3 = ['2']
l4 = ['B']
l5 = ['3']
l6 = ['C']

listoflists = [l1,l2,l3,l4,l5,l6]
itr = iter(listoflists)

f = open ('order.txt','w')

while True: 
    try:
           itr.next()
           s = str(itr.next())
           f.write(str('\n'))
           f.write(s)

    except StopIteration:
        break
f.close()
+1  A: 

Your code could be a lot simpler:

for list in listoflists:
    f.write(str(list))
    f.write('\n')

But, this is going to print something like ['1']. It seems like you want something more like:

for list in listoflists:
    f.write(str(list[0]))
    f.write('\n')

Also, why do you have a bunch of single-element lists? Couldn't you put all the elements into one list?

danben
Regarding the single-element lists, the code might have been simplified for clarity.
mizipzor
Not forgetting the line endings...
MattH
@danben Thanks and @mizipzor you are right.. I had single element lists because it represents a real simplification of a script I have that pulls some data out of a sqlite db...one list has the date field and the other list has the contents of another field... I am probably doing that in some horribly inefficient way as well...but it's working -- so I am not messing with it!
CaseyIT
+5  A: 

First of all, don't use iter and next(), that's what for is for. Secondly, you are actually writing a list to the file, not its contents. So you could either print the first element of the list (i.e. l1[0]) or iterate through all the inner lists elements.

Your code should look like this:

l1 = ['1']
l2 = ['A']
l3 = ['2']
l4 = ['B']
l5 = ['3']
l6 = ['C']

listoflists = [l1,l2,l3,l4,l5,l6]

f = open ('order.txt','w')

for inner_list in listoflists:
    for element in inner_list:
        f.write(element+'\n')

f.close()
sttwister
Thanks, I like this solution.. There are some nice alternatives below as well..but I like the verbosity of this, since I tend to forget how I have done things as time goes by...
CaseyIT
+2  A: 

I think the best way to solve this is just with a basic nested loop. Try this:

l1 = ['1']
l2 = ['A']
l3 = ['2']
l4 = ['B']
l5 = ['3']
l6 = ['C']
listoflists = [l1,l2,l3,l4,l5,l6]

f = open("out.txt","w")

# for each list and
# for each item in the list;
# write the item to the file, separated by a comma
for list in listoflists: 
    for item in list: 
        f.write(item+",") 

f.close()

Out.txt now holds:

1,A,2,B,3,C,

Oh, and no Python question is complete without a one-liner solution (this also removes the trailing comma from my initial response).

open("out.txt","w").write(",".join(("".join(i) for i in listoflists)))

Out.txt now holds:

1,A,2,B,3,C
mizipzor
You can remove the brackets in the one-liner solution - saves memory by using a generator instead of creating a list object.
AndiDog
Fixed. Although I prefer brackets since I find them easier to read, its already quite a jungle of special characters there, making most of them parenthesis doesn't help. And you have to work with pretty big lists in order to notice the memory gain. Feel free to edit my answer by the way if you can see room for improvement. :)
mizipzor
He didn't mean replace the brackets with parentheses, he meant remove the brackets. You only need two layers of parentheses in your write().
Jeffrey Harris
A: 

Including the quotes in the output is a bit odd, but if you insist:

for entry in listoflists:
  print >>f, repr(entry[0])

You don't specify what will happen if the inner list does not have just one element, so any other possibility is ignored here.

Ignacio Vazquez-Abrams
A: 

You can simply iterate through all list elements with itertools.chain (documented here):

import itertools

l1 = ['1']
l2 = ['A']
l3 = ['2']
l4 = ['B']
l5 = ['3']
l6 = ['C']

chainedlists = itertools.chain(l1,l2,l3,l4,l5,l6)

with open ('order.txt','wt') as f:
    for element in chainedlists:
        # Change this how you want it to be formatted, it will output
        # a string "a" as 'a' (with the quotes)
        f.write("%s\n" % repr(element))
AndiDog
+1  A: 

The simple reason why you are getting the wrong file contents is because you are calling iter twice. Lines 15-16 are:

itr.next()
s = str(itr.next())

For more Pythonic printing semantics, see the other answers

DoctorRuss