creating a csv from information I have printed to screen
Ciar?n Hudson wrote:
> How do I edit the code below to create a csv file which includes the
> information I have printed at the bottom?
> I'm pulling arrival data from an airport website and printing out only the
> flight info. I want to save that flight info to a CSV file.
First of all the data in the html is already structured as a table.
You really want to keep that structure instead of reconstructing it from the
for row in table:
write cells in row
Then you have to decide on the columns
> print('Arriving From', 'Airline', 'Scheduled to arrive','Latest
and I guess they are what you print above. Once you have the data creating
the csv is easy, Python includes a module for it. So:
import csv, sys
writer = csv.writer(sys.stdout)
'Scheduled to arrive', 'Latest Update', 'Status'
[table] = soup.find_all("table")
for row in table.find_all("tr"):
[td.string.strip() for td in row.find_all("td")]
To write to a file instead of stdout pass the writer a file
with open("flight.csv", "w") as f:
writer = csv.writer(f)
> cells = soup.find_all('td')
> for cell in cells:
> for content in cell.contents:
> value = str(content).strip().replace('\n', '')
> if len(value) == 0:
> print('"0"', end=',')
> elif value.lower() in 'abcdefghijklmnopqrstuvwxyz<':
> print('\n' + value, end=',')
> print('"' + value + '"', end=',')