Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading