簡體   English   中英

通過 collums/rows 將數據附加到現有 CSV 文件

[英]Appending data to existing CSV file by collums/rows

我正在嘗試將數據導出到 csv。 當我導出它時,它被導出為單個行,並且每個附加數據都附加在同一行上。 結果是非常長的行,難以導航。

目標是讓每個值(時間、錢包)都有自己的 collum,並且每次運行腳本時,新數據都會附加到相應 collum 下的 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()

正如 Shubham P. 指出的那樣,最小的解決方法是通過包含換行符來確保您正在編寫“行”,例如'\n'

file = open('dogedata.csv', 'a')
file.write(f'{current_time},{num_of_wallets}\n')
file.close()

正如 martineau 所指出的,更好的解決方法是使用csv模塊:它是標准的,經過良好開發和使用,重要的是解決了 escaping 和引用字符等問題,並且只需要多行:

file = open('dogedata.csv', 'a', newline='')
writer = csv.writer(f)
writer.writerow([current_time, num_of_wallets])
file.close()

請注意, newline=''被添加到open() function 中,它告訴 open() 不要處理換行符,而是遵從具有 CSV 特定智能處理 w/換行符的編寫

此外,您只需將數據包裝在一個列表中( [current_time, num_of_wallets] ),而不是使用字符串格式; 作者會將所有內容轉換為字符串/文本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM