繁体   English   中英

如何读取文件的一部分

[英]How to read a part of a 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.

我该怎么做?

您可以只读取文件,直到到达空行,如下所示:

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

您可以在段落处拆分文件并像这样打印其中任何一个:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM