[英]Import Data from scraping into CSV
我正在使用 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)
嘗試使用熊貓,
import pandas as pd
interest_over_time_df.to_csv("file.csv")
一旦我遇到同樣的問題並像下面這樣解決它:
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)。
你可以嘗試這樣的事情:
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
您需要遍歷數據並逐行寫入
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.