File as TextReader

From IronPython Cookbook

This recipe shows how to inherit .NET TextReader class, in order to pass Python's file-like objects to .NET API.

The entire example is available in FePy SVN.

from System.IO import TextReader

class PythonFileReader(TextReader):
    def __init__(self, f):
        self.f = f
    def Read(self, buffer, index, count):
        chars = self.f.read(count).ToCharArray()
        chars.CopyTo(buffer, index)
        return len(chars)

For example, you can create XmlReader from Python file. The following example prints names of all tags in test.xml.

import clr
clr.AddReference('System.Xml')

from System.Xml import XmlReader

f = open('test.xml')
fr = PythonFileReader(f)
xr = XmlReader.Create(fr)

while xr.Read():
    if xr.IsStartElement(): print xr.Name,
print

Back to Contents.

TOOLBOX
LANGUAGES