我正在嘗試將資料匯出到 csv 中。當我匯出它時,它被匯出為單個行,并且每個附加資料都附加在同一行上。結果是非常長的行,難以導航。
目標是讓每個值(時間、錢包)都有自己的列,并且每次運行腳本時,新資料都會附加到相應列下的 csv 中。我已經嘗試了在線指南,但無法找到任何解決方案。
如果有人有任何建議或想法,這是我的代碼。此外,如果有人對重組我的代碼或使其更好有任何建議,我很想聽聽。作為初學者,我想盡可能多地學習。
#Open ChromeDriver
PATH = ('/Users/chris/Desktop/chromedriver')
driver = webdriver.Chrome(PATH)
#Get Website
driver.get("https://bitinfocharts.com/top-100-richest-dogecoin-addresses.html")
driver.implicitly_wait(5)
driver.maximize_window()
#Creates the Time
now = datetime.now()
current_time = now.strftime("%m/%d/%Y, %H:%M:%S ")
#Identify the section of page
time.sleep(3)
page = driver.find_element(By.CSS_SELECTOR,'.table.table-condensed.bb')
#Gather the data
time.sleep(3)
num_of_wallets = page.find_element(By.XPATH, "//html/body/div[5]/table[1]/tbody/tr[10]/td[2]").text
#Write to CSV
table_dict = {"Time":current_time,
"Wallets":num_of_wallets}
headers = ["Time", "Wallets"]
file = open('dogedata.csv', 'a')
file.write(f'{current_time},{num_of_wallets}')
file.close()
uj5u.com熱心網友回復:
正如 Shubham P. 指出的那樣,最小的解決方法是通過包含換行符來確保您正在撰寫“行”,例如'\n':
file = open('dogedata.csv', 'a')
file.write(f'{current_time},{num_of_wallets}\n')
file.close()
正如 martineau 所指出的,更好的解決方法是使用csv模塊:它是標準的、經過良好開發和使用的,重要的是可以處理轉義和參考字符等問題,而且只需要多行:
file = open('dogedata.csv', 'a', newline='')
writer = csv.writer(f)
writer.writerow([current_time, num_of_wallets])
file.close()
請注意,它newline=''已添加到open()函式中,它告訴 open() 不要處理換行符,而是遵從具有 CSV 特定智能處理 w/換行符的撰寫器。
此外,您只需將資料包裝在串列中([current_time, num_of_wallets]),而不是使用字串格式;作者會將所有內容轉換為字串/文本。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/417046.html
標籤:
上一篇:匹配2個CSV檔案(根據列)
