0

I have a text file that contains a lot of data. I want to be able to read the text file and write a new text file. However on the new text file I don't want it to include some part of the orginal.

For example the text file has

------------------------
Age: 39
Gender: Female
Smoking: Yes
remarks: something about the person
-----------------------
Age: 52
Gender: Male
Smoking: Yes
remarks: something about the person
-----------------------

How do I get the new file to only read in age and gender so that the new text file will look like (also including the dashes that are divide each entry):

-----------------------
Age: 39
Gender: Female
-----------------------
Age: 52
Gender: Male
-----------------------

I've seen a couple of codes and other questions but they all are not just removing specific lines.

1
  • If there are always 5 lines per entry, just do not write every 4th and 5th line. Commented Jul 17, 2014 at 16:32

2 Answers 2

5
with open('path/to/infile') as infile, open('path/to/outfile', 'w') as outfile:
    for line in infile:
        if line.startswith(("Age", "Gender", "----")):
            outfile.write(line)

Alternatively with grep:

grep -ioP '^-.*$|^Age:.*$|^Gender:.*$' path/to/infile.txt > path/to/outfile.txt
Sign up to request clarification or add additional context in comments.

1 Comment

@StevenRumbalski You can even drop the any, str.startswith accepts a tuple
0
import re

file = open('filename.txt','rb').read()

a = re.findall(r'Age: (\d+)\nGender: (Male|Female)', file)

print "-----------------------"
for n in a:
    print 'Age: '+n[0]+'\nGender: '+n[1]
    print "-----------------------"

You can be even lazier and grab the Dashes in the regex too

a = re.findall(r'Age: (\d+)\nGender: (Male|Female)(?:.*\n){3}(\-*)', file)

for n in a:
    print "Age: "+n[0]+ "\nGender: "+n[1]+"\n" + n[2]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.