0

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)
Hrvoje T
  • 3,365
  • 4
  • 28
  • 41
  • 2
    Why can't you just write `myBytesVar` to the file and re-use it with `myVar = myBytesVar.decode('utf-8')`? – Blender Apr 12 '18 at 07:00
  • Thanks. Do I need utf8 if I have coding:utf-8 at the beginning of a script? – Hrvoje T Apr 12 '18 at 07:09
  • By "with one `with`" do you mean that something like this is acceptable: `with open("myFile.txt", "wb") as outFile, open("myFile.txt", "r") as inFile:`? This should work, although it's just syntactic sugar for a double `with`. – Giacomo Alzetta Apr 12 '18 at 07:10
  • 1
    @HrvojeT: The encoding that your Python script file itself uses and the encoding your `myFile.txt` uses are two completely different things. – Blender Apr 12 '18 at 07:12

3 Answers3

2

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.

Blender
  • 289,723
  • 53
  • 439
  • 496
0

If you want to do it with one "with": When you write it "wb" is good. when you read the file try it

myvar = open('MyVar.txt', 'r').read()
print(myvar)
Sraw
  • 18,892
  • 11
  • 54
  • 87
Jay Pratap Pandey
  • 352
  • 2
  • 9
  • 19
0

Here is some information on what mode we should use :

The default mode is 'r' (open for reading text, synonym of 'rt'). For binary read-write access, the mode 'w+b' opens and truncates the file to 0 bytes. 'r+b' opens the file without truncation.

Read more here. https://docs.python.org/3/library/functions.html#open

toheedNiaz
  • 1,435
  • 1
  • 10
  • 14