1

我正在使用 python 脚本运行一个 unix 命令,我将它的输出(多行)存储在一个字符串变量中。现在,我必须使用该多行字符串将其分成三个部分(由模式End---End分隔)来制作 3 个文件。

这就是我的输出变量包含的内容

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

现在我想要三个文件 file_A、file_B 和 file_C 用于输出的这个值:-

file_A的内容

Text for file_A
something related to file_A

文件_B的内容

Text for file_B
something related to file_B

文件_C的内容

Text for file_C
something related to file_C

此外,如果 Output 没有其各自文件的任何文本,那么我不希望创建该文件。

例如

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

现在我只想创建 file_B 和 file_C,因为 file_A 没有文本

文件_B的内容

Text for file_B
something related to file_B

文件_C的内容

Text for file_C
something related to file_C

如何在python中实现这个?是否有任何模块可以使用某些分隔符对多行字符串进行分区?

谢谢 :)

4

2 回答 2

2

您可以使用以下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',
 '']

'End---End'由于末尾有 a ,所以最后一个拆分返回'',所以可以指定拆分的数量:

>>> 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']
于 2015-01-06T14:23:38.387 回答
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)
于 2015-01-06T14:32:09.690 回答