如何阅读文件的一部分

时间:2016-03-10 21:58:47

标签: python file

我有一个文件,我想只打印其中的第一段。

这是我的档案:

Once upon a midnight dreary, while I pondered, weak and weary,
  Over many a quaint and curious volume of forgotten lore--
  While I nodded, nearly napping, suddenly there came a tapping,
  As of some one gently rapping, rapping at my chamber door.
  "'Tis some visitor," I muttered, "tapping at my chamber door--
                                     Only this and nothing more."

  Ah, distinctly I remember it was in the bleak December,
  And each separate dying ember wrought its ghost upon the floor.
  Eagerly I wished the morrow;--vainly I had sought to borrow
  From my books surcease of sorrow--sorrow for the lost Lenore--
  For the rare and radiant maiden whom the angels name Lenore--
                                     Nameless here for evermore.

我该怎么做?

2 个答案:

答案 0 :(得分:0)

您可以直接读取文件,直至找到空行,如下所示:

with open('filename.txt') as f:
    for line in f:
       if line == '':  # exit when you reach the end of the first paragraph
           break 
       print line

答案 1 :(得分:0)

您可以在段落中拆分文件并打印其中任何一个,如下所示:

with open('foo.txt') as f:
    paragraphs = f.read().split('\n\n')
    print(paragraphs[0])