簡體   English   中英

使用Python生成數據並導出到Excel文件

[英]Generate data using Python and export to excel file

我是一個初學者。 這會從URL生成“正確的”數據,但是當我嘗試生成CSV文件時,結果Excel文件為空。 這是代碼...

import csv
import urllib.request
from bs4 import BeautifulSoup

f = open('dataoutput.csv', 'w', newline = "")
writer = csv.writer(f)

soup = BeautifulSoup(urllib.request.urlopen("https://www.rjobrien.co.uk/tools/quoteresult/symbol/FGBLM8").read(), 'lxml')

tbody = soup('table', {"class": "table table-bordered table-condensed"})[0].find_all('tr')

for row in tbody:
    cols = row.findChildren(recursive=False)
    cols = [ele.text.strip() for ele in cols]

writer.writerow(cols)

您的意思是將writerow()放在循環之后嗎? 如所寫,它將僅產生最后一行。

我假設您稍后再執行f.close() 我建議使用with將在作用域末尾關閉文件。 例如,

with open('dataoutput.csv', 'w', newline = "") as f:
    writer = csv.writer(f)
    ...

您應該使用與循環相同的標識縮進<tab>writer.writerow(cols)

完成寫入文件后,應使用f.close() Python應該自動執行此操作,但是您不知道何時執行該操作,並且您正在使用系統資源(並行打開的文件數量有限)。

最終,您可以添加為第一行: sep=,這樣您就不會對使用不同的Excel語言環境產生任何問題。 參見https://superuser.com/questions/407082/easiest-way-to-open-csv-with-commas-in-excel

暫無
暫無

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

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