Elly
Elly

Reputation: 1

Python: extract sections from a text file and write them into new separate text files

Sorry for the dummy questions here.

In python, I have a input text file as in the picture here textfile, which includes 3 sections of text, and I need to first find all the lines in the bottom of each section of the text that includes "shsux/en", and then under this section, I would like to loop back and search for all the lines that start with "udp" and "jkp", and output the whole section into a new text file.

But I'm a beginner in Python and I'm not sure what would be the best way to achieve this. Appreciate any kindly reply.

Upvotes: 0

Views: 1795

Answers (2)

Paulius Baranauskas
Paulius Baranauskas

Reputation: 343

I would do something like this:

out_big = f.open(first_output_file, "w")
out_small_1 = f.open(second_output_file, "w")
out_small_2 = f.open(third_output_file, "w")
with open(source_file, "r") as f:
    for line in f:
        if "shsux" in line:
            out_big.write(line)
            if line.startswith("udp"):
                out_small_1.write(line)
            elif line.startswith("jkp"):
                out_small_2.write(line)
out_big.close()
out_small_1.close()
out_small_2.close()

But I think the big file with "shsux" is not necessary, so you could skip it.

Sorry, made a mistake, and used endswith(), instead of startswith.

Upvotes: 0

Axel Puig
Axel Puig

Reputation: 1334

Something like this?

file1 = open('file1.txt', 'w')

with open('source.txt', 'r') as source_file:
    for line in source_file:
        if 'shsux' in line:
            file1.write(line)
        # Same for other files...

file1.close()

Upvotes: 1

Related Questions