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.
Eg
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 :)
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']
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.