簡體   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