ralphie9224 ralphie9224 - 1 month ago 4x
Python Question

Writing values to excel csv in python

I have the below code where I'm trying to write values to an excel file, but my output adds one letter in every single column, instead of the whole word, like so
enter image description here

I want the whole word to be in one column. I'm currently passing in an array that has the words

[u'Date / Time', u'City', u'State', u'Shape', u'Duration', u'Summary']
into my
. How can I make it so that I get the whole word in one column?

import requests
import csv
from bs4 import BeautifulSoup

r = requests.get('http://www.nuforc.org/webreports/ndxlAK.html')
soup = BeautifulSoup(r.text, 'html.parser')

f = open('ufo.csv', 'wb')
writer = csv.writer(f)

headers = soup.find_all('th')
header_text = []
header_count = 1
for header in headers:
if header_count == len(headers):
print "value being written: " + str(header_text)
header_count += 1



You're extracting the text of a single column via:

for header in headers

For each single column, you're writing it out like a row of columns via:


The writerows method expects a list of columns to write, so it iterates over it. You've passed it a single string, so it iterates over that and writes one character per column.

So either:

writer.writerows([header_text])  # turn this single column into a list
# or
writer.writerow(header_text)  # just write out as a single item

should work.