如何用python编写字典列表的csv

时间:2018-08-04 14:20:13

标签: python csv dictionary data-analysis

print(test[0].keys())
keys = test[0].keys()
with open('work.csv', 'w') as output_file:
    dict_writer = csv.DictWriter(output_file, keys)
    dict_writer.writeheader()
    dict_writer.writerows(test)

def get_user_category(user_polarity, followers_polarity, following_polarity):
if user_polarity and followers_polarity == following_polarity:
    return following_polarity
elif user_polarity and following_polarity == followers_polarity:
    return followers_polarity
elif followers_polarity and following_polarity == user_polarity:
    return user_polarity 

def get_users_tweet(username):
user_tweet = user_csv[user_csv["user"] == username]["tweets"]
user_tweet = list(user_tweet)
return user_tweet

def convertDictToCSV(dictionary):
w = csv.writer(open("output.csv", "w"))
for key, val in dictionary.items():
    w.writerow([key,val])
    return "Written to csv"

def get_maximum_class(username):
l = []
w = {}
for x in user_csv[user_csv["user"] == username ]["labels"]:
    l.append(x)
for z in set(l):
    w[z] = l.count(z)
return max(w)

def get_maximum_class_for_followers(username):
l = []
w = {}
for x in followers_csv[followers_csv["user"] == username ]["labels"]:
    l.append(x)
for z in set(l):
    w[z] = l.count(z)
return max(w)

def get_maximum_class_for_followed_users(username):
l = []
w = {}
for x in follow_csv[follow_csv["follows"] == username ]["labels"]:
    l.append(x)
for z in set(l):
    w[z] = l.count(z)
return max(w)

def get_followers_and_class_max(user):     多数= []     user_followers =设置(followers_csv [followers_csv [“关注”] ==用户] [“用户”])     user_followers_class =设置(followers_csv [followers_csv [“关注”] ==用户] [“标签”])     对于user_followers中的each_user:         多数。附加(get_maximum_class_for_followers(每个用户))     返回max(多数)

def get_follow_follow_max(user):
majority = []
users_followed = set(follow_csv[follow_csv["user"] == user]["follows"])
users_followed_class = set(follow_csv[follow_csv["user"] == user]["follows"])
for each_user in users_followed:
    majority.append(get_maximum_class_for_followed_users(each_user))
return max(majority)

test = [] 对于set(user_csv [“ user”])中的each_user:     尝试:         followers_polarity = get_followers_and_class_max(每个用户)     除了(ValueError):         followers_polarity = 0     尝试:         following_polarity = get_follow_follow_max(每个使用者)     除了(ValueError):         following_polarity = 0

user_category = get_user_category(get_maximum_class(each_user), followers_polarity, following_polarity)
users_tweet = get_users_tweet(each_user)
data = {"User:": each_user, "Polarity: ": get_maximum_class(each_user), "Following Polarity: ": following_polarity,            "Followers Polarity: ": followers_polarity, "Users Category: ": user_category }
test.append(data)

打印(测试)

new_file =StringIO(newline='')   

#print(test[0].keys())
keys = test[0].keys()
with open('work.csv', 'w') as output_file:
    dict_writer = csv.DictWriter(output_file, keys)
    dict_writer.writeheader()
    dict_writer.writerows(test)
with open('work3','w',newline='') as f_out:
    f_out.write(output_file.getvalue())

我想用新字段创建一个新的csv文件。分类显示在终端上,但未创建新的csv文件。

1 个答案:

答案 0 :(得分:0)

您可以使用StringIO类(docs here)写入内存(不创建任何文件),然后写入终端。本示例将CSV数据写入StringIO对象并打印:

import csv
from io import StringIO   # from StringIO import StringIO in case of Python2

test = [{'col1':1, 'col2':2, 'col3':3},
        {'col1':4, 'col2':5, 'col3':6}]

output_file = StringIO(newline='')

dict_writer = csv.DictWriter(output_file, ['col1', 'col2', 'col3'])
dict_writer.writeheader()
dict_writer.writerows(test)

output_file.seek(0)
print(output_file.read())

打印:

col1,col2,col3
1,2,3
4,5,6

编辑:

要写入多个CSV文件,您可以使用以下代码段:

import csv
from io import StringIO

test = [{'col1':1, 'col2':2, 'col3':3},
        {'col1':4, 'col2':5, 'col3':6}]

output_file = StringIO(newline='')

dict_writer = csv.DictWriter(output_file, ['col1', 'col2', 'col3'])
dict_writer.writeheader()
dict_writer.writerows(test)

with open('work1.csv', 'w', newline='') as f1_out, \
    open('work2.csv', 'w', newline='') as f2_out:

    f1_out.write(output_file.getvalue())
    f2_out.write(output_file.getvalue())

这将创建两个文件work1.csvwork2.csv