2016-03-10 4 views
-1

У меня есть файл, и я хочу напечатать только первый абзац в нем.Как прочитать часть файла

Это мой файл:

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. 

Как мне это сделать?

+1

Как вы открываете файлы в Python? Как вы читаете файлы? Что разделяет абзацы? Как вы разделили строку на этот разделитель? Сначала ответьте на эти вопросы для себя, затем вы будете вооружены, чтобы задать хороший вопрос. В названии даже не точно описывается то, что вы хотите сделать. –

ответ

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 
+0

@jorrede, пожалуйста, подумайте о принятии ответа, если это было полезно для вас, нажав галочку. – Forge

0

вы можете разделить файл на абзацы и распечатать любой из них, как это:

with open('foo.txt') as f: 
    paragraphs = f.read().split('\n\n') 
    print(paragraphs[0]) 
Смежные вопросы