1

I'm running a unix command using python script, I'm storing its output (multi-line) in a string variable. Now I have to make 3 files using that multi-line string by partitioning it into three parts (Delimited by a pattern End---End).

This is what my Output variable contains

Output = """Text for file_A
something related to file_A
End---End
Text for file_B
something related to file_B
End---End
Text for file_C
something related to file_C
End---End"""

Now I want to have three files file_A, file_B and file_C for this value of Output:-

contents of file_A

Text for file_A
something related to file_A

contents of file_B

Text for file_B
something related to file_B

contents of file_C

Text for file_C
something related to file_C

Also if Output doesn't have any text for its respective file then I don't want that file to be created.

E.g

Output = """End---End
Text for file_B
something related to file_B
End---End
Text for file_C
something related to file_C
End---End"""

Now I only want file_B and file_C to be created as there is no text for file_A

contents of file_B

Text for file_B
something related to file_B

contents of file_C

Text for file_C
something related to file_C

How can implement this in python? Is there any module to partition a multi-line string using some delimeter?

Thanks :)

2 Answers 2

2

You can use the split() method:

>>> pprint(Output.split('End---End'))
['Text for file_A\nsomething related to file_A\n',
 '\nText for file_B\nsomething related to file_B\n',
 '\nText for file_C\nsomething related to file_C\n',
 '']

Since there is a 'End---End' at the end, the last split returns '', so you can specify the number of splits:

>>> pprint(Output.split('End---End',2))
['Text for file_A\nsomething related to file_A\n',
 '\nText for file_B\nsomething related to file_B\n',
 '\nText for file_C\nsomething related to file_C\nEnd---End']
Sign up to request clarification or add additional context in comments.

2 Comments

upvoted the answer as it seems the question is a homework question so would hesitate to do more than hint.
thanks! duh!! I should really stop coming to this forum high :D This justifies my name 8-)
0
Output = """Text for file_A
something related to file_A
End---End
Text for file_B
something related to file_B
End---End
Text for file_C
something related to file_C
End---End"""

ofiles = ('file_A', 'file_B', 'file_C')

def write_files(files, output):
    for f, contents in zip(files, output.split('End---End')):
        if contents:
            with open(f,'w') as fh:
                fh.write(contents)

write_files(ofiles, Output)

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.