PDA

Archiv verlassen und diese Seite im Standarddesign anzeigen : Python Binary Mode


cv
2014-06-09, 19:22:30
Ich habe eine Frage bezüglich des Unterschieds des Binary Modes zwischen Python 2.7.6 und 3.4.0.

Folgender Code
datei = "h.wav"
#datei = input("Datei?: ")
dat = open(str(datei), "rb")
li = []

def daten_zu_bytes():
# Verwandelt eine Datei in eine "Byte-Liste"
try:
byte = dat.read(1)
print (byte)
while byte != '' and byte != "":
li.append(ord(byte))
byte = dat.read(1)
finally:
dat.close()
return li


daten_zu_bytes()

Gibt unter 2.7.6 folgendes aus :
R

Process finished with exit code 0


Unter 3.4.0 jedoch folgendes:
b'R'
Traceback (most recent call last):
File "...", line 20, in <module>
daten_zu_bytes()
File "...", line 13, in daten_zu_bytes
li.append(ord(byte))
TypeError: ord() expected a character, but string of length 0 found

Process finished with exit code 1

Daher die erste Frage was ist der unterschied von R zu b'R'.
2. was sagt die Fehlermeldung aus bzw was ist anders und löst die Fehlermeldung aus
3. Wie krieg ich das behoben?

Vielen Dank für die Hilfe :)

Gast
2014-06-09, 21:08:51
https://stackoverflow.com/questions/1035340/reading-binary-file-in-python

cv
2014-06-09, 22:21:13
Der Code funktioniert nur in 2.7.x (man beachte das Datum). Er sieht ja auch so aus wie meiner. ;)

Dr.Doom
2014-06-10, 09:22:40
str vs bytes in Python 3.x

http://python3porting.com/problems.html#binary-section

cv
2014-06-10, 11:48:59
Danke hat geklappt :)

Dr.Doom
2014-06-10, 11:56:30
Zeig' mal.