python - 如何防止记录在python csv的单元格中多次附加?
问题描述
我一直在检索 twitter 实时数据,我想将推文的某些字段提取到 csv,其中一行代表一条推文;tweetid 和推文文本。一切正常,直到我将推文文本附加到 csv 中,突然多个推文被插入到推文文本单元格中。
我打印了 tweetid、计数器和文本,它打印出每行最多 12000 条记录。
但是,在 csv 文件中,由于这个问题,我丢失了 200 条记录。我添加了一个计数器来识别和跟踪我丢失 200 条记录的位置。我被困了几个小时。有人可以帮我找出问题所在吗?
这是我的代码:
with client:
with open('data.csv', 'w', newline='', encoding='utf-8', errors='ignore') as file:
fw = csv.writer(file, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
fw.writerow(['CollectionId', 'Counter', 'Text'])
print('starting to append data to csv...')
counter = 0
print('appending Streaming data...')
for stream in Streaming:
streamTime = stream["created_at"]
parseTime = dateutil.parser.parse(streamTime)
# CollectionId
if stream["id_str"]:
collectionId = "'" + stream["id_str"] + "'"
counter = counter + 1
# cleanup text - to display in a single line
streamText = stream["text"]
streamText = streamText.split('\n') #remove new lines in text
streamText = " ".join(streamText)
streamText = streamText.replace(',', ' ') #replace commas in text
#print("{}, {} - {}".format(collectionId, counter, streamText))
fw.writerow([collectionId, counter, streamText])
print("Streaming Data has been exported to 'data.csv'")
解决方案
推荐阅读
- c++ - 设备注册表属性更改时接收通知
- windows - 如何输出一个持续激活的 CMD
- excel - Excel:Flashfill 偏移水平 + 垂直
- java - 与标准应用程序概念共享存储
- android - 当用户从通知中取消下载时,DownloadManager 的意图是什么?
- r - 从 R 数据框中提取逗号分隔值
- apache-spark - 如何通过计算列的总和并除以常数来创建新列 - pyspark
- reactjs - React Material-UI 和颜色:警告
- python - 如何将 python 2.7.16 替换为 python 3?
- javascript - 如何删除嵌套 foreach 中的循环数组值?