1

I am curious how this Try and Except work in python after running into this error:

def for_file(data):
    open_file = file('data.txt', 'w')
    try:
        open_file.write(data)
    except:
           print 'This is an error!'
    open_file.close()

Output: This is an error!

def for_file(data):
    try:
        open_file = file('data.txt', 'w')
        open_file.write(data)
        print 'Successful!'
    except:
           print 'This is an error!'
    open_file.close()

Output: Successful!

How is it possible?

Error: 'ascii' codec can't encode characters in position 15-16: ordinal not in range(128)

I am receiving data in unicode form. what should I do?

Hemant
  • 619
  • 2
  • 6
  • 17
  • 2
    Would you add `import traceback; traceback.print_exc()` to the `except` clause and add the output to the question? – bereal Mar 07 '13 at 12:47
  • What's the error? your `except` block will catch anything. – msvalkon Mar 07 '13 at 12:48
  • I have added that error. data received is in the form of unicode. using str() not helpful.. – Hemant Mar 07 '13 at 13:36
  • @Hemant that doesn't explain why it works in the first example and does not work in the second one. Are you running both snippets with the same data? – bereal Mar 07 '13 at 13:39
  • 1
    First read *"The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets"* http://www.joelonsoftware.com/articles/Unicode.html – Jakub M. Mar 07 '13 at 13:47

3 Answers3

3

To write unicode data to a file, use codecs.open() instead:

import codecs

with codecs.open('data.txt', 'w', 'utf-8') as f:
    f.write(data)
bereal
  • 32,519
  • 6
  • 58
  • 104
1

You are getting a TypeError. When you write to the file, 'data' needs to be a string or buffer. Your second function also won't work if you don't pass it a string or buffer (I tried them both passing them a 2, neither worked). The below code works.

 def for_file(data):
    open_file = file('data.txt', 'w')
    try:
        open_file.write(str(data))
        print "Success!"
    except:
        import traceback; traceback.print_exc() #I used this to find the error thrown.
        print 'This is an error!'
    open_file.close()
Wesley Bowman
  • 1,366
  • 16
  • 35
  • If "neither worked", you didn't reproduce the OP's situation. – bereal Mar 07 '13 at 13:08
  • OP didn't inform us as to what input he used for either. I just kind of assumed he changed between the two. If not, (i.e. he passed a string) then both should have worked. I can't do anything more without his input. – Wesley Bowman Mar 07 '13 at 13:14
  • @NightHallow: Yup u r right. I am getting data in unicode form. str() not working.. – Hemant Mar 07 '13 at 13:38
0

You may need to print the error message to figure out what's the problem:

def for_file(data):
    open_file = file('data.txt', 'w')
    try:
        open_file.write(data)
    except Exception as e:
        print 'This is an error!'
        print e
    open_file.close()