Define class to deal with files : File Text « File « Python






Define class to deal with files


class FileStrings:
    def __init__(self, filename=None, data=None):
        if data == None:
            self.data = open(filename).read()
        else:
            self.data = data
        self.paragraphs = self.data.split('\n\n')
        self.lines = self.data.split('\n')
        self.words = self.data.split()
    def __repr__(self):
        return self.data
    def paragraph(self, index):
        return FileStrings(data=self.paragraphs[index])
    def line(self, index):
        return FileStrings(data=self.lines[index])
    def word(self, index):
        return self.words[index]

bigtext = FileStrings('a.txt')
print bigtext.paragraph(0)

print bigtext.line(0)

print bigtext.line(-4)

print bigtext.word(-4)

print bigtext.paragraph(2).line(2).word(-1)

           
       








Related examples in the same category

1.Adding Line Numbers to a Python Script