@@ -252,3 +252,38 @@ def bencode(value):
252252# Method proxies (for compatibility with other libraries)
253253decode = bdecode
254254encode = bencode
255+
256+ def bread (fd ):
257+ """
258+ return bdecoded data from filename, file, or file-like object
259+
260+ if fd is a bytes/string or pathlib.Path-like object, it is opened and
261+ read, otherwise .read() is used. if read() not available, exception
262+ raised.
263+ """
264+ if isinstance (fd , (bytes , str )):
265+ with open (fd , 'rb' ) as fd :
266+ return bdecode (fd .read ())
267+ elif isinstance (fd , (pathlib .Path , pathlib .PurePath )):
268+ with open (str (fd ), 'rb' ) as fd :
269+ return bdecode (fd .read ())
270+ else :
271+ return bdecode (fd .read ())
272+
273+ def bwrite (data , fd ):
274+ """
275+ write data in bencoded form to filename, file, or file-like object
276+
277+ if fd is bytes/string or pathlib.Path-like object, it is opened and
278+ written to, otherwise .write() is used. if write() is not available,
279+ exception raised.
280+ """
281+ if isinstance (fd , (bytes , str )):
282+ with open (fd , 'wb' ) as fd :
283+ fd .write (bencode (data ))
284+ elif isinstance (fd , (pathlib .Path , pathlib .PurePath )):
285+ with open (str (fd ), 'wb' ) as fd :
286+ fd .write (bencode (data ))
287+ else :
288+ fd .write (bencode (data ))
289+
0 commit comments