osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

creating a csv from information I have printed to screen


Ciar?n Hudson wrote:

> This has helped a lot; cleaner output, keeping tbl format and creating a
> csv but the csv is not being populated. Any idea what I am doing wrong?

> writer = csv.writer(sys.stdout)
> writer.writerow([
>     'Arriving From'
>     'Airline',
>     'Scheduled to arrive', 'Latest Update', 'Status'
>     ])
> 
> #cells = soup.find_all('td')
> #print(cells)
> 
> [table] = soup.find_all("table")
> for row in table.find_all("tr"):
>     writer.writerow(
>         [td.string.strip() for td in row.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[0].lower() in 'abcdefghijklmnopqrstuvwxyz<':
> #             print('\n' + value, end=',')
> #         else:
> #             print('"' + value + '"', end=',')
>             
>             
>             
>             
> with open('flight.csv','w') as f:
>     writer = csv.writer(f)

Well you open the file and create a writer but you don't write anything. You 
need this part

      [table] = soup.find_all("table")
      for row in table.find_all("tr"):
          writer.writerow(
              [td.string.strip() for td in row.find_all("td")]
          )

inside the with-suite, too. 

If you are interested in learning Python, you may put it into a function and 
invoke it twice, with the writer writing to stdout and the writer writing to 
the file.