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 =
        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

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,

Back to Contents.