【问题标题】:Import Data from scraping into CSV将数据从抓取导入 CSV
【发布时间】:2018-10-03 13:12:38
【问题描述】:

我正在使用 pycharm 和 Python 3.7。

我想在 csv 中写入数据,但我的代码仅在文件中写入数据的第一行...有人知道为什么吗?

这是我的代码:

from pytrends.request import TrendReq
import csv


 pytrend = TrendReq()
 pytrend.build_payload(kw_list=['auto model A', 
 'auto model C'])


# Interest Over Time
interest_over_time_df = pytrend.interest_over_time()
print(interest_over_time_df.head(100))



writer=csv.writer(open("C:\\Users\\
Desktop\\Data\\c.csv", 'w', encoding='utf-8'))

writer.writerow(interest_over_time_df)

【问题讨论】:

  • 你确实看到你已经通过执行writer.writerow而不是在循环中写入了一行代码。
  • @Pdf 你用的是哪个版本的python?
  • @pygo Python 3.7
  • 好的,如果你和平时的 with open 核对,那么试试我发布的可能有帮助的答案。

标签: python csv screen-scraping


【解决方案1】:

尝试使用熊猫,

import pandas as pd
interest_over_time_df.to_csv("file.csv")

【讨论】:

  • 只是出于好奇,我可以避免 pandas 的导入吗?
  • @PdF,如果您使用 pandas 的功能和属性,则无法避免导入,但是如果您不想使用 pandas,您可以避免。
  • 好的,我知道这一点,但是当我粘贴您的代码时,导入带有红色下划线,因为我没有在代码中调用库...
  • @Pdf ,如果您首先从中提取数据框,则必须导入 pandas .. :-)
【解决方案2】:

一旦我遇到同样的问题并像下面这样解决它:

with open("file.csv",  "rb", encoding="utf-8) as fh:

具体细节:

r = read mode
b =  mode specifier in the open() states that the file shall be treated as binary, 
so contents will remain a bytes. No decoding attempt will happen this way.

众所周知,python 尝试将字节数组(它假定为 utf-8 编码字符串的字节)转换为 unicode 字符串 (str)。这个过程当然是按照utf-8规则进行解码。当它尝试这样做时,它会遇到一个 utf-8 编码字符串中不允许的字节序列(即位置 0 处的这个 0xff)。

【讨论】:

    【解决方案3】:

    你可以试试这样的:

    import csv
    with open(<path to output_csv>, "wb") as csv_file:
        writer = csv.writer(csv_file, delimiter=',')
        for line in interest_over_time_df:
            writer.writerow(line)
    

    在此处阅读更多信息:https://www.pythonforbeginners.com/files/with-statement-in-python

    需要循环遍历数据,逐行写入

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-22
      • 1970-01-01
      • 2017-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-22
      • 2015-02-07
      相关资源
      最近更新 更多