Search code examples
pythonextract

How to extract a single line in a TXT file


I already have a code that extracts the subject line of a letter from a txt file:

import os
ans = []

for filename in os.listdir(os.getcwd()):
   with open(os.path.join(os.getcwd(), filename), 'r') as rf:
    for line in rf:
        line = line.strip()
        if line.startswith("subject"):
            ans.append(line)
        elif line.startswith("Subject"):
           ans.append(line)
    
with open('extracted_data.txt', 'w') as wf:
    for line in ans:
        wf.write(line)

However, it gets formatted like this:

subject: Block 8 of EricssonSubject: Block 9 of Ericssonsubject: Block 10 of Ericssonsubject: Block 11 of Ericsson

When I want it to look like this:

subject: Block 8 of Ericsson
Subject: Block 9 of Ericsson
subject: Block 10 of Ericsson
subject: Block 11 of Ericsson

How do I get it to format in the above desired way?


Solution

  • replace

    with open('extracted_data.txt', 'w') as wf:
        for line in ans:
            wf.write(line)
    

    to

    with open('extracted_data.txt', 'w') as wf:
        for line in ans:
            wf.write(line+'\n')