0

I have some code that was written for Python 3 that I am trying to make Python 2.7 compatible. In Python 3, the code f.seek(0, SEEK_END) returns 320816 but in Python 2, the same code returns None. When I print the part of the file I'm interested in I get a bunch of lines of the form b'NEUEVLBL\x90\x00ainp16\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' which leads me to believe that the error has something to do with Python 2.7 reading this as a regular string as opposed to a bytes literal and possibly something to do with Python 2.7's use of \ as an escape character (not the case in Python 3). Does anyone have any suggestions?

EDIT: Before anyone suggests it, yes, I've tried 3to2

G Warner
  • 1,309
  • 1
  • 15
  • 27
  • `file.seek()` is documented to return `None` in python2. The string looks like a proper byte array to me. Is the last slash really in the printout? – dhke Mar 12 '15 at 18:13
  • No, I cut off a bunch of it because it just kinda went on, and on, and on. There is no `\` at the actual end. I'm confused, it _always_ returns `None` in Python 2? What is the purpose of that? In my code, `f.seek`'s output (an int in Python 3) is used as a param later on. How do I get the same int in Python 2? – G Warner Mar 12 '15 at 18:18
  • That's because in Python2 it's a direct implementation of the underlying `fseek()` call which also does not return the new position in the file. `file.tell()` can be used to obtain that value. Also see answer from @Ignacio below. – dhke Mar 12 '15 at 18:25

1 Answers1

2

You're using open() to open the file in 2.7, but that will not return a file object whose seek() method returns the new file pointer location. Use io.open() instead.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358