简体   繁体   English

在python中分割多行字符串

[英]Partitioning multiline string in python

I'm running a unix command using python script, I'm storing its output (multi-line) in a string variable. 我正在使用python脚本运行unix命令,并将其输出(多行)存储在字符串变量中。 Now I have to make 3 files using that multi-line string by partitioning it into three parts (Delimited by a pattern End---End ). 现在,我必须使用该多行字符串将其分为三个部分(由模式End --- End分隔)来制作3个文件。

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:- 现在,我想使用三个文件file_A,file_B和file_C作为此Output值:

contents of file_A file_A的内容

Text for file_A
something related to file_A

contents of file_B file_B的内容

Text for file_B
something related to file_B

contents of file_C 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. 另外,如果Output的相应文件没有任何文本,则我不希望创建该文件。

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 现在我只希望创建file_B和file_C,因为没有file_A的文本

contents of file_B file_B的内容

Text for file_B
something related to file_B

contents of file_C file_C的内容

Text for file_C
something related to file_C

How can implement this in python? 如何在python中实现呢? Is there any module to partition a multi-line string using some delimeter? 是否有任何模块可以使用一些定界符对多行字符串进行分区?

Thanks :) 谢谢 :)

You can use the split() method: 您可以使用split()方法:

>>> 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: 由于'End---End'有一个'End---End' ,最后一个分割返回'' ,因此您可以指定分割数:

>>> 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM