【问题标题】:Appending data to existing CSV file by columns/rows按列/行将数据附加到现有 CSV 文件
【发布时间】:2022-01-19 01:39:29
【问题描述】:

我正在尝试将数据导出到 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()

【问题讨论】:

  • 您是否考虑过使用 Pandas 数据框来存储数据?然后根据需要将其导出到 csv 非常容易(请参阅文档here)
  • 在您当前的file.close() 之前添加一个file.write('\n')。每当您编写时,这应该会创建一个新行
  • 您应该使用标准库中的csv 模块来创建文件。它是内置的、经过调试的且易于使用。

标签: python csv


【解决方案1】:

正如 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() 不要处理换行符,而是遵从 writer 处理 w/换行符。

此外,您只需将数据包装在一个列表中([current_time, num_of_wallets]),而不是使用字符串格式;作者会将所有内容转换为字符串/文本。

【讨论】:

    猜你喜欢
    • 2020-12-14
    • 2020-12-26
    • 2020-06-05
    • 2013-08-03
    • 2021-07-21
    • 2017-06-30
    • 2014-05-03
    • 1970-01-01
    相关资源
    最近更新 更多