Search code examples
pythonencodingasciifile-writing

Writing to a file but getting ASCII encoding error


I am trying to scrape data from a table on a website.

page_soup = soup(html, 'html.parser')
stat_table = page_soup.find_all('table')
stat_table = stat_table[0]

with open ('stats.txt','w') as q:
for row in stat_table.find_all('tr'):
    for cell in row.find_all('td'):
        q.write(cell.text)

However, when I try to write the file, I get this error message: 'ascii' codec can't encode character '\xa0' in position 19: ordinal not in range(128).

I understand that it should be encoded with .encode('utf-8'), but

cell.text.encode('utf-8')

doesn't work.

Any help would be greatly appreciated. Using Python 3.6


Solution

  • The file encoding is determined from the current Environment, in this case assuming ascii. You can specify the file encoding directly use:

    with open ('stats.txt', 'w', encoding='utf8') as q:
        pass