35684

UnicodeEncodeError: 'cp949' codec can't encode character

Question:

How do I handle this?

wfile.write(data['text']+'\n')

UnicodeEncodeError: 'cp949' codec can't encode character

import tweepy import time import os import json search_term1 = '' search_term2 = '' lat = "" lon = "" radius = "" location = "%s,%s,%s" % (lat, lon, radius) auth = tweepy.OAuthHandler(API_key, API_secret) auth.set_access_token(Access_token, Access_token_secret) api = tweepy.API(auth) c=tweepy.Cursor(api.search, q="{}+OR+{}".format(search_term1, search_term2), rpp=1000, geocode=location, include_entities=True) wfile = open(os.getcwd()+"/test1.txt", mode='w') data = {} i = 1 for tweet in c.items(): data['text'] = tweet.text print(i, ":", data) wfile.write(data['text']+'\n') time.sleep(0.5) i += 1 wfile.close()

I get this error by modifying the Internet.

TypeError: write() takes no keyword arguments

wfile.write(data['text']+'\n',encoding='UTF8')

TypeError: write() takes exactly one argument (2 given)

wfile.write(data['text']+'\n','utf-8')

Answer1:

cp949 is the default locale for your Windows system, and that's what open() defaults to. From the <a href="https://docs.python.org/3/library/functions.html#open" rel="nofollow">open() documentation</a>:

<blockquote>

<em>encoding</em> is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent (whatever locale.getpreferredencoding() returns), but any text encoding supported by Python can be used.

</blockquote>

Specify a different codec when opening the file:

wfile = open(os.getcwd()+"/test1.txt", mode='w', encoding='utf8')

Note that you don't need to pre-pend os.getcwd() when opening a file without a path, the default is to use the working directory for relative paths:

wfile = open("test1.txt", mode='w', encoding='utf8')

You'd be better off using os.path.join() to build paths for everything else.

Your code can otherwise be simplified further with enumerate() and a context manager. The data dictionary is not really useful here, just reference tweet.text everywhere:

with open(os.getcwd()+"/test1.txt", mode='w') as wfile: for i, tweet in enumerate(c.items()): print("{}: {}".format(i, tweet.text)) wfile.write(tweet.text + '\n') time.sleep(0.5)

Recommend

  • Using Tweepy API behind proxy
  • Putting Twitter Widget's Javascript within tags, but have it rendered in
  • UnicodeEncodeError: 'cp949' codec can't encode character
  • Twitter atom don't retrieving old tweets
  • tkinter.TclError: character U+1f449 is above the range (U+0000-U+FFFF) allowed by Tcl
  • Tweepy: tweepy.error.tweeperror 'code' 215 'message' 'bad authentication da
  • Where to exclude retweets in this tweepy script?
  • Tweepy: simple script with 'Bad Authentication data' error
  • script for window.location.href error
  • Stopping Tweepy stream after a duration parameter (# lines, seconds, #Tweets, etc)
  • PHP SoapClient __getFunctions() returning UNKNOWN types
  • trying to get location from address using google api v3
  • Google Places Autocomplete Vue.js
  • Returning value from function inside a function
  • Uber API - requests endpoint cannot read read json
  • Pre-populated SQLite Database not reading properly in Android Studio
  • Converting query results into DataFrame in python
  • Possible to get mouse events fired when cursor is outside page?
  • Selenium to click on a javascript button corresponding to a text
  • Google Custom Search with transparent background
  • Insert into database using onclick function
  • What is Eclipse's Declaration View used for?
  • Fill an image in a square container while keeping aspect ratio
  • Can I make an Android app that runs a web view in Chrome 39?
  • Font Awesome Showing Box instead of Icons
  • Properly structure and highlight a GtkPopoverMenu using PyGObject
  • Circular dependency while pushing http interceptor
  • File not found error Google Drive API
  • Is it possible to post an object from jquery to bottle.py?
  • Python/Django TangoWithDjango Models and Databases