Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

write() argument must be str, not bytes [duplicate]

I'm a beginner programmer and am working through the book python for the absolute beginner. I have come across a problem trying to write a high scoring function for the trivia game. when the function 'highscore(user, highscore):' is called on I try to assign the arguments accordingly so I can pickle the information to a file for later use. however I am running into an error trying to dump the info needed.

def highscore(user, highscore):
    '''stores the players score to a file.'''
    import pickle, shelve
    user = ''
    highscore = 0
    #Hscore = shelve.open('highscore.dat', 'c')
    Hscore = open('highscore.txt', 'a')
    pickle.dump(user, Hscore)
    pickle.dump(highscore, Hscore)
    #Hscore.sync()
    Hscore.close()

since I'm working through the book and have also seen shelves in action I tried using them too but run into their own set of errors. so ignore the '#'s at this time.

at the part pickle.dump is where I'm generating an error. I keep getting (as the title suggests) a write argument error.

I don't understand why its not recognizing them as string. as when they are defined in the main function it is indeed a string..

like image 426
Austin Howard Avatar asked Jul 22 '16 10:07

Austin Howard


People also ask

How to fix write() argument must be str not bytes?

The Python "TypeError: write() argument must be str, not bytes" occurs when we try to write bytes to a file without opening the file in wb mode. To solve the error, open the file in wb mode to write bytes or decode the bytes object into a string.

Can only concatenate str not bytes to str?

The Python "TypeError: can only concatenate str (not "bytes") to str" occurs when we try to concatenate a string and a bytes object. To solve the error, decode the bytes object into a string before concatenating the strings.


1 Answers

Looks like you are working through a book aimed at Python 2. You need to open your file in binary mode; add b to the mode:

Hscore = open('highscore.txt', 'ab')

If your book contains more issues like these, it may be time to switch to one that supports Python 3 or to install Python 2.7 at least for the purposes of completing the book exercises.

like image 117
Martijn Pieters Avatar answered Oct 19 '22 12:10

Martijn Pieters