4

I need to convert a string from a file that I have into an integer. The string in question is just one number.

L= linecache.getline('data.txt', 1)
L=int(L)  

print L   

I receive the error:

ValueError: invalid literal for int() with base 10: '\xef\xbb\xbf3\n'

How do I convert this string into an integer?

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • 3
    @MattBall No duplicate at all. What you linked has nothing to do with the unexpected BOM which bothers the author of this question. – Hyperboreus Oct 07 '13 at 03:21

2 Answers2

5

The file contains an UTF-8 BOM.

>>> import codecs
>>> codecs.BOM_UTF8
'\xef\xbb\xbf'

linecache.getline does not support encoding.

Use codecs.open:

with codecs.open('data.txt', encoding='utf-8-sig') as f:
    L = next(f)
    L = int(L)
    print L   
falsetru
  • 357,413
  • 63
  • 732
  • 636
4

Your file starts with a BOM. Strip it before trying to parse the number.

Hyperboreus
  • 31,997
  • 9
  • 47
  • 87