Ukii Ukii - 6 months ago 21
Python Question

Python copy all lines before string in another text file

I have stacked in my code, I want from this code to open file that already exists with huge text (inputt), read it and If line contains "***" then copy lines before it and paste in another file (outputt).

My inputt file for example looks like this:

This is the house

this is the flower

this is a tree

'***'

This is a car

this is an apple

this is the nature

'***'


So my goal is to copy all lines before "***" and paste it in another file. So it can be separated into two files. Here is my stacked code:

def transform(inputt, outputt):
with open(inputt) as f, open(outputt, "w") as f1:
count = 0
for line in f:
if "***" in line:
f.writelines(deque(f1, count))
else:
count = count + 1

Answer

Its not really clear what you are trying to accomplish. Given your description and example input file, it sounds like you would want the following written to outputt:

This is the house

this is the flower

this is a tree

Is that correct? If so:

def transform(inputt, outputt):
    with open(inputt) as f, open(outputt, "w") as f1:
        f1.write(f.read().split("***")[0])

This code has a number of flaws, but without a better description it's hard to really know what you're after.

Edit: Given the response in the comments:

def transform(inputt, outputt_base):
    with open(inputt, "r") as f:
        for count, block in enumerate(f.read().split("***")):
            outputt_name = outputt_base + "_{0}.txt".format(count)
            with open(outputt_name, "w") as f1:
                f1.write(block)

Given your example input file, this would write two output files: (Assuming outputt_base is just the string output)

First file: output_1.txt

This is the house

this is the flower

this is a tree

and

Second file: output_2.txt

This is a car

this is an apple

this is the nature