2

Say I have an object called obj that is initialized and has 50 member variables. I want to write this to a row in a csv file without having to type out every member variable of the object. The long winded way to do this I want to avoid would be:

writerPosts.writerow([obj.var1, obj.var2, obj.var3 .........................]) 

I want to do something instead that looks like this and achieves the same result:

writerPosts.writerow(obj)

How can this be done?

sometimesiwritecode
  • 2,993
  • 7
  • 31
  • 69

2 Answers2

2

One way of getting all class fields/variables is as following:

members = [attr for attr in dir(obj) if not callable(getattr(obj, attr)) and not attr.startswith("__")]

Here members is list of all the possible variables. The above list comprehension filters out any callable attributes (means any possible functions of the class) and any built-in functions.

Then it is simple to write them to your csv file.

with open("output.csv",'wb') as resultFile:
    wr = csv.writer(resultFile, dialect='excel')
    wr.writerows(members)

This will write those variables (not values) to the csv file.

EDIT: If you want to write values of the variables, then you can do the following:

values = [getattr(obj, member) for member in members]

The values list will have values for your each class fields. Then you can write this list to csv file, as above.

Nabin
  • 11,216
  • 8
  • 63
  • 98
1

I'm going to assume you have a number of these objects and write a little example. vars() can be used to get the member variables of a class instance:

import csv

class Class:
    def __init__(self,a,b,c,d,e):
        self.var1 = a
        self.var2 = b
        self.var3 = c
        self.var4 = d
        self.var5 = e

# Create a few objects with different member values...
L = [Class(1,2,3,4,5),Class(2,3,4,5,6),Class(3,4,5,6,7)]

with open('out.csv','w',newline='') as f:

    # fieldnames lists the headers for the csv.
    w = csv.DictWriter(f,fieldnames=sorted(vars(L[0])))
    w.writeheader()

    for obj in L:
        # Build a dictionary of the member names and values...
        w.writerow({k:getattr(obj,k) for k in vars(x)})

Output:

var1,var2,var3,var4,var5
1,2,3,4,5
2,3,4,5,6
3,4,5,6,7
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251