Kodi Community Forum
How to use xbmcvfs.File() and io.open()? - Printable Version

+- Kodi Community Forum (https://forum.kodi.tv)
+-- Forum: Development (https://forum.kodi.tv/forumdisplay.php?fid=32)
+--- Forum: Add-ons (https://forum.kodi.tv/forumdisplay.php?fid=26)
+---- Forum: Python 3 migration (https://forum.kodi.tv/forumdisplay.php?fid=281)
+---- Thread: How to use xbmcvfs.File() and io.open()? (/showthread.php?tid=327871)



How to use xbmcvfs.File() and io.open()? - Wimpie - 2018-01-31

Hi,

I want my addon to be able to read text files on nfs:// and smb:// shares.

For this I need xbmcvfs.File().

So what is the xbmcvfs.File() equivalent of:

python:
import io
 
with io.open('foo.txt', 'r', encoding='utf-8') as fo:
text = fo.read()

Thanks!

PS: I read the sticky, but I don't even know where to start to combine these 2 'open' functions...


RE: How to use xbmcvfs.File() and io.open()? - Roman_V_M - 2018-01-31

Syntax is the same for Python 2 and 3:
python:
from contextlib import closing
from xbmcvfs import File

with closing(File('/path/to/file')) as fo:
    text = fo.read()

However, the big catch is that the current Python 2 implementation returns a binary string, but in Python 3 .read() methods decodes text using UTF-8 encoding (that is the default for Python 3). For binary data you need to use .readBytes().

I can also suggest this helper library https://github.com/romanvm/kodi.six that normalizes string handling in Python 2 and 3.