在我們實際業務開發中,肯定會遇到將集合對象的數據遍歷完後寫入到數據庫或者導出為一個csv文件裡,如下是一個具體實現的示例demo
import pandas as pd
class Test:
calorie = 0
duration = 0
flag = 0
def init_object():
""" init class atrributes :return: list """
test = Test()
test.calorie = 20
test.duration = 50
test.flag = 1
list = []
# add obj to list
list.append(test.__dict__)
test = Test()
test.calorie = 30
test.duration = 60
test.flag = 0
# add obj to list
list.append(test.__dict__)
print(list)
return list
def obj_csv( obj_list):
""" :param obj_list: :return: csv """
# convert list to Dataframe
df = pd.DataFrame(obj_list)
print(df)
# take dataframe to csv file
df.to_csv("output.csv", index=None)
obj_list = init_object()
obj_csv(obj_list)