python - 如何解决 csv.DictWriter 覆盖 csv 中的数据?
问题描述
我正在尝试抓取 Twitter 以获取某些用户的关注者/朋友数量。我有大量用户要查看。我实际上想将输出收集到字典中,然后将输出写入 CSV 文件。我尝试了 pandas (dict -> dataframe -> csv) 和 (dict -> CSV) 路由,但我一直在写入失败。
我的代码如下:
# Writing directly from Dictionary to CSV
auth = tweepy.OAuthHandler(api_key, api_secret_key)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth, wait_on_rate_limit=True,
wait_on_rate_limit_notify=True)
# *Just a sample of the large user list I want to check out*
z =['Schwarzenegger', 'drdrew', 'NPR', 'billboard', 'SenJohnMcCain', 'LaurenJauregui', 'MarkRuffalo']
for i in z:
user_dict = {}
follower_count = api.get_user(i).followers_count
friend_count = api.get_user(i).friends_count
# print(i, follower_count, friend_count)
# create a dictionary to hold values
user_dict[i] = follower_count, friend_count
# Write dictionary into csv file
cols = ["username", "followers_count"]
try:
with open('details.csv', 'w', newline='', encoding='utf8') as f:
writer = csv.DictWriter(f, fieldnames=cols)
writer.writeheader()
for data,val in user_dict.items():
writer.writerows([{"username": data, "followers_count": val}])
except IOError:
print("I/O error")
#Notify me when operation is completed
print("file write completed")
输出>>>文件仅包含最后一个条目:
MarkRuffalo,"(6674117, 1852)"
Dict -> DF -> csv 路由还生成了一个只有标题但内容为空的文件:
df = pd.DataFrame(user_dict, columns = ["follower_count","friend_count"])
print(df)
df.to_csv('user_files.csv', header=True)
请问我该怎么做才能确保所有字典条目都写入文件。谢谢你。PS:我对所有这些都是新手,所以我的写作可能会很尴尬。
解决方案
- 在 open() 语句之后的 for 循环中放置“cols”
- 将 for 循环(for i in z:) 放在 writeheader() 语句之后的“try”中
- 删除这一行:“for data,val in user_dict.items():”
- 在您的 writerow 变量中使用 API 变量(来自 for 循环)(“writerow”不是复数 - 删除末尾的“s”)
这些资源将帮助您:
在 Python 中遍历字典: https ://realpython.com/iterate-through-dictionary-python/
读取和写入 CSV 文件:https ://realpython.com/python-csv/
我最终尝试了它并且它有效。我为它可能关闭的缩进道歉
# Write dictionary into csv file
try:
with open('details.csv', node='w') as f:
cols = ["username", "followers_count","friends_count"]
writer = csv.DictWriter(f, fieldnames=cols)
writer.writeheader()
for i in z:
user_dict = {}
follower_count = api.get_user(i).followers_count
friend_count = api.get_user(i).friends_count
# print(i, follower_count, friend_count)
# assign values
user_dict[i] = follower_count, friend_count
#write to each row
writer.writerow({cols[0]:i, cols[1]:follower_count, cols[2]:friend_count})
except IOError:
print("I/O error")
#Notify me when operation is completed
print("file write completed")
对于 Panda DataFrame:我使用下面的方法让它工作 - 但没有标题在单独的列中显示字典键 + 值
df = pd.DataFrame(data=user_dict)
print(df)
df.to_csv('user_files.csv', header=True)
第三个示例 - 现在使用 Transpose 在单独的行上显示字典键+值
df = pd.DataFrame(data = user_dict)
df = df.T
print(df)
df.to_csv('user_files2.csv', header=True)
您将不得不使用这些列标题
我的资源: https ://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html
推荐阅读
- android - 防止 CardView 中的 RecyclerView 拦截触摸
- php - 如何使用 for 循环创建从 mysql 数据库填充的可折叠 html/bootstrap 复选框表?
- hyperlink - scrapy docs作者蜘蛛无法抓取内部链接
- docker - 如何将一个 docker 容器上的端口绑定到另一个 docker 容器上的端口?
- javascript - 为什么我在运行代码时收到错误“UnhandledPromiseRejectionWarning”?
- python - 使用 Keras 实现图像金字塔
- android - 为每个新项目包含相同的依赖项
- react-native - React-Native 按钮无法导航到下一页
- javascript - 创建 MVC 格式的动态元素
- json - 如何将带有嵌套数组的 JSON 对象映射到打字稿模型中?