Home > python > python – TypeError: coercing to Unicode:

python – TypeError: coercing to Unicode:

Problem:
Was getting the following error. Did not understand why it kept on complaining about receiving a list when I clearly passed on a csv file.
The name of my file is update_records and I would run it as follows on the command line.

shell> ./update_records.py records.csv

Traceback (most recent call last):
File “./update_records.py”, line 156, in
main()
File “./update_records.py”, line 130, in main
subscriber_data = _get_data(input_file)
File “./update_records.py”, line 44, in _get_data
csvdata = csv.reader(open(csvfile, “r”))
TypeError: coercing to Unicode: need string or buffer, list found

I finally realised that at some other point in my code I do

122         opts, args = getopt.getopt(sys.argv[1:], '', ['help'])
123 
124         for opt, arg in opts:
125             if opt in ('--help'):
126                 _help()
127 
128         input_file = args

input_file now contains the list [‘records.csv’] and that is what is passed on to csv.reader(open(csvfile, “r”)) in csvfile and that is what generates the error.

Solution:
Changed input_file = args to input_file = args[0] to pick the first item from args.

122         opts, args = getopt.getopt(sys.argv[1:], '', ['help'])
123 
124         for opt, arg in opts:
125             if opt in ('--help'):
126                 _help()
127 
128         input_file = args[0] # Fixed!

Advertisements
Categories: python
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: