返回顶部

收藏

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)

标签:Python,File

收藏

0人收藏

支持

0

反对

0

»更多 您可能感兴趣的代码
  1. 2016-12-24 10:24:24Reading a file: readlines and xreadlines by 张宋付
  2. 2016-01-02 10:12:28Copy file and move dir by Solon.Ring
  3. 2016-11-27 10:13:11Reading the newly created file. by 山药
  4. 2016-11-27 14:14:10File readline() by 张宋付
  5. 2015-02-23 09:40:23ubuntu安装python3的python-pip by 甄码农
  6. 2013-06-04 13:43:27web.py中自定义jinja2模块 by 赵小全
  7. 2015-11-27 20:36:13Iterating Over Lines with readlines by 张宋付
  8. 2016-01-04 17:35:46Closing Files by 西国の海妖
  9. 2016-08-19 15:46:08Working with Directories by 西国の海妖
  10. 2016-09-03 11:47:53Define function to Open a file by 阮小七
  11. 2016-09-19 19:25:12File Output by jack.chen

发表评论