2016-05-20 17 views
0
#!/usr/bin/env python3 

f = open('dv.bmp', mode='rb') 
slika = f.read() 
f.closed 

pic = slika[:28] 
slika = slika[54:] 
# dimenzije originalnog bitmapa 
pic_w = ord(pic[18]) + ord(pic[19])*256 
pic_h = ord(pic[22]) + ord(pic[23])*256 
print(pic_w, pic_h) 

warum dieser Code in python3 nicht funktioniert (in python2 es funktioniert gut) OR Howto Binärdatei in String-Typ in python3 lesen?in python2 ist in Ordnung, aber in python3 funktioniert nicht

+0

Was genau ist das Problem? Wie scheitert es? – Mureinik

+0

Traceback (zuletzt letzter Aufruf): Datei "./open file 2.py", Zeile 14, in pic_w = ord (Bild [18]) + ord (Bild [19]) * 256 TypeError: ord() erwartete Zeichenfolge der Länge 1, aber int gefunden –

+0

Entfernen Sie einfach ord(), es ist redundant in dieser Vorsicht, weil Python 3 Bytes als Ganzzahlen –

Antwort

0

In Python 2.x, Binär-Modus (zB 'rb') wirkt sich nur, wie Python interpretiert end-of-line Zeichen:

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb' , 'wb' , and 'r+b' . Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn’t hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files.

jedoch in Python 3.x, Binär-Modus auch die Art der resultierenden Daten ändert:

Normally, files are opened in text mode, that means, you read and write strings from and to the file, which are encoded in a specific encoding. If encoding is not specified, the default is platform dependent (see open()). 'b' appended to the mode opens the file in binary mode: now the data is read and written in the form of bytes objects. This mode should be used for all files that don’t contain text.

Da das Lesen in einem Byte-Objekt resultiert, führt die Indizierung zu einer Ganzzahl und nicht zu einer Zeichenfolge wie in Python 2. Wenn diese Ganzzahl an die ord()-Funktion übergeben wird, wird der Fehler ausgelöst erwähnt in your comment. Die Lösung besteht darin, den ord() Aufruf in Python 3 wegzulassen, da die Ganzzahl, die Sie durch das Indizieren des Bytes-Objekts erhalten, die gleiche ist wie die, die Sie beim Aufrufen von ord() für die Zeichenkette erhalten würden.

Verwandte Themen