0

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 writer. 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')
csv.register_dialect('excel')

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)
        writer.writerows(header_text)
    else:
        header_text.append(header.text)
        header_count += 1

f.close()
2
  • writer.writerows([header_text]) ? Commented Sep 9, 2016 at 20:41
  • That works, why do the [] make a difference? Commented Sep 9, 2016 at 20:43

1 Answer 1

2

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:

writer.writerows(header_text)

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.