Search code examples
pythonfilehandler

In Python, how to use a file for writing bytes in it and reading as text


I would like to save bytes to a file and then read that file as a text. Can I do it with one with? What should I use, wb, r or wbr?

myBytesVar = b'line1\nline2'
with open('myFile.txt', 'wb') as fw:
    fw.write(myBytesVar)

with open('myFile.txt', 'r') as fr:
    myVar = fr.read()
    print(myVar)

Solution

  • You don't need to re-read the file if you already have its contents stored in myBytesVar:

    myBytesVar = b'line1\nline2'
    
    with open('myFile.txt', 'wb') as fw:
        fw.write(myBytesVar)
    
    myVar = myBytesVar.decode('utf-8')
    

    The encoding Python assumes when reading files as text without an explicit encoding is platform-dependent, so I'm just assuming UTF-8 will work.