1

I'm trying to write a large number of fields from a Class to a csv. E.g.

for i in range(0,  len(t)):
    t.writerow([t[i].a,  t[i].b,  t[i].c,...]

However I have a subclass which I also want to write at the end of this list:

for i in range(0,  len(t)):
    t.writerow([  t[i].a,  t[i].b,  t[i].c,...  t[i].z[0].s,  t[i].z[1].s ...])

However I'm not sure how I achieve this, the subclasses are of varying lengths, so how would I ensure that each row just appends the relevant number of subclasses at the end? I can't find anything in the documentation about it. Do I make a string out of the subclass entries, and then just paste one entry at the end? Thanks.

1
  • It's very hard to read your sample code, please add some whitespace to make it more obvious where the things begin and end. Oh, and three dots ... is sufficient. Thanks. Commented Dec 2, 2012 at 0:08

2 Answers 2

1

I think writing it something like this would work:

for i in range(len(t)):
    row = [[ e.a, e.b, e.c, ...] + [e.z[0], e.z[1], e.z[2], ...] for e in t[i]]
    t.writerow(row)
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, I had gone and made an empty list and appended with a for loop , but that looks a lot nicer!
1

If z is just a python list, just append it to the list of fields from t:

t.writerow([t[i].a, t[i].b, t[i].c, ...] + t[i].z)

which would be the same as [one, list] + [another, list].

It looks like you can just loop over t (a list) itself instead of using a range():

for item in t:
    t.writerow([item.a, item.b, item.c, ...] + item.z)

2 Comments

Thanks Martijn. It's not quite a list. It's a subclass as in t.z[1].s, t.z[2].s.... I tried what you suggested but that didn't work. That was my fault, I've edited the OP
I could make t.z.s into a list though and then add it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.