Windows用户在这里!我正在使用pycharm和Python 3.7。
我想在csv中写入数据,但是我的代码仅将数据的第一行写在File中……有人知道为什么吗?
这是我的代码:
from pytrends.request import TrendReq
import csv
pytrend = TrendReq()
pytrend.build_payload(kw_list=['Mercedes-Benz Classe A',
'Mercedes-Benz Classe 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\\p.de.falco\\
Desktop\\Tesi\\Data\\c.csv", 'w', encoding='utf-8'))
writer.writerow(interest_over_time_df)
先谢谢你!
答案 0 :(得分:0)
尝试使用熊猫
import pandas as pd
interest_over_time_df.to_csv("file.csv")
答案 1 :(得分:0)
一旦我遇到相同的问题,并按如下所示解决它:
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)。
答案 2 :(得分:0)
您可以尝试以下方法:
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
您需要遍历数据并逐行写