-1

I'm trying to figure out how I can open a file via a pathvariable in binary mode.

So basically I want instead of:

open(b'picklefile.p', 'wb')

this

path = /picklefiles/picklefile.p

open(b'path', 'wb')

I tried to solve this by leaving the b out but apparently, things go wrong. I wasn't able to find a way that allows me to use a variable as every available example uses the direct path, am I overlooking something or is it not possible so I need to convert it somehow?

quamrana
  • 37,849
  • 12
  • 53
  • 71
  • The variable name is `path`, not `b'path'` or `'path'`. And to assign a string to path you use `path = '/picklefiles/picklefile.p'`. – jarmod Jul 05 '21 at 12:53

2 Answers2

0

All you have to do is to assign the string name of a path to a variable and then use that variable:

path = b'/picklefiles/picklefile.p'

file = open(path, 'wb')
quamrana
  • 37,849
  • 12
  • 53
  • 71
0

b is basically calling the bytes() function on the string. more info here

>>> path = "test.txt"
>>> f = open(bytes(path, "ascii"), "r")
>>> f.readline()
'testing testing \n'
DaiShogun
  • 20
  • 5