Connor Bailey
Connor Bailey

Reputation: 69

TypeError when writing to .txt file Python

I'm taking data from a website, and writing it to a .txt file.

head = 'mpg123 -q '
tail = ' &'

url = 'http://www.ndtv.com/article/list/top-stories/'
r = requests.get(url)
soup = BeautifulSoup(r.content)

g_data = soup.find_all("div",{"class":"nstory_intro"})
log = open("/home/pi/logs/newslog.txt","w")
soup = BeautifulSoup(g_data)

# Will grab data from website, and write it to .txt file
for item in g_data:
        shorts = textwrap.wrap(item.text, 100)
        text_file = open("Output.txt", "w")
        text_file.write("%s" % g_data)

        print 'Wrote Data Locally On Pi'
        text_file.close()

        for sentance in shorts:
                print 'End.'
    #               text_file = open("Output.txt", "w")
    #               text_file.close()

I know the website pulls the correct information, however, when I run it in the console, I keep getting this error:

TypeError: 'ResultSet' does not have the buffer interface

I tried looking around on Google, and I'm seeing this a lot for strings in a TypeError: 'str' does not have the buffer interface between Python 2.x and Python 3.x. I tried implementing some of those solutions within the code, but It still keep getting the 'ResultSet' error.

Upvotes: 0

Views: 130

Answers (1)

cuongnv23
cuongnv23

Reputation: 382

ResultSet is type of your g_data:

In [8]: g_data = soup.find_all('div',{'class':'nstory_intro'})

In [9]: type(g_data)
Out[9]: bs4.element.ResultSet

You better use context manager to handle the open and close automatically.

If you just want to write text content of g_data to Output.txt, you should do this:

with open('Output.txt', 'w') as f:
    for item in g_data:
        f.write(item.text + '\n')

Upvotes: 1

Related Questions