首页 > 解决方案 > 如何防止记录在python csv的单元格中多次附加?

问题描述

我一直在检索 twitter 实时数据,我想将推文的某些字段提取到 csv,其中一行代表一条推文;tweetid 和推文文本。一切正常,直到我将推文文本附加到 csv 中,突然多个推文被插入到推文文本单元格中。

我打印了 tweetid、计数器和文本,它打印出每行最多 12000 条记录。

但是,在 csv 文件中,由于这个问题,我丢失了 200 条记录。我添加了一个计数器来识别和跟踪我丢失 200 条记录的位置。我被困了几个小时。有人可以帮我找出问题所在吗?

这是我的工作 csv 的屏幕截图: 在此处输入图像描述

这就是问题: 在此处输入图像描述

这是我的代码:

      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'")

标签: pythonpython-3.xcsvtwitter

解决方案


推荐阅读