Python stops reading file using read

后端 未结 2 328
感情败类
感情败类 2021-01-20 12:52

I\'m trying to read a binary file and am getting confusing results.

f = open(\'foo.dat\',\'r\')

data = f.read()

print len(data), f.tell()

相关标签:
2条回答
  • 2021-01-20 13:22

    It's probably on Windows and you have a Ctrl-Z (the CP/M end-of-file marker, which was inherited by Windows via MS-DOS). Do this:

    f = open('foo.dat','rb') # NOTE b for binary
    data = f.read() 
    print len(data), f.tell() 
    print repr(data[60:70])
    

    and show us the output. Ctrl-Z is '\x1a' aka chr(26).

    0 讨论(0)
  • 2021-01-20 13:23

    data is a str object, thus len(data) tells you about the length of this string, not the file length in bytes.

    0 讨论(0)
提交回复
热议问题