Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 当有空行分隔时,如何将一个txt文件拆分为两个单独的txt文件?_Python_Python 3.x_File_Text Editor - Fatal编程技术网

Python 当有空行分隔时,如何将一个txt文件拆分为两个单独的txt文件?

Python 当有空行分隔时,如何将一个txt文件拆分为两个单独的txt文件?,python,python-3.x,file,text-editor,Python,Python 3.x,File,Text Editor,当出现白线时,如何将单个.txt文件拆分为两个或多个.txt文件 下面是我的txt的示例: a s d d d d s d f f d e s s a d f s a s d d d d s d f f d e s s a d f s dsdesd dseesdse 我想知道如何将此单个文本文件拆分为: 第一个txt文件: a s d d d d s d f f d e s s a d f s a s d d d d s d f f d e s s a d f s dsdesd dsees

当出现白线时,如何将单个.txt文件拆分为两个或多个.txt文件

下面是我的txt的示例:

a s d d d d s d f
f d e s s a d f s
a s d d d d s d f
f d e s s a d f s

dsdesd
dseesdse
我想知道如何将此单个文本文件拆分为:

第一个txt文件:

a s d d d d s d f
f d e s s a d f s
a s d d d d s d f
f d e s s a d f s
dsdesd
dseesdse
第二个txt文件:

a s d d d d s d f
f d e s s a d f s
a s d d d d s d f
f d e s s a d f s
dsdesd
dseesdse

如果您知道文件只有一个空行,则可以在双换行符处添加内容:

with open('input.txt') as f:
    contents = f.read()

output1, output2 = contents.split('\n\n')

with open('output1.txt', 'w') as o1:
    o1.write(output1)

with open('output2.txt', 'w') as o2:
    o2.write(output2)
如果文件有多个空行,这将失败,因为拆分将返回两个以上的部分,并尝试将它们仅分配给两个名称,
output1
output2
。可以被告知只拆分最大次数,因此更安全的说法是:

output1, output2 = contents.split('\n\n', 1)
如果有两个或多个空行,
output1
将是第一个空行之前的内容<代码>输出2将是第一个空行之后的所有内容,包括任何其他空行


当然,如果没有空行,此操作可能会失败。

如果您知道文件只有一个空行,则可以在双换行符处添加内容:

with open('input.txt') as f:
    contents = f.read()

output1, output2 = contents.split('\n\n')

with open('output1.txt', 'w') as o1:
    o1.write(output1)

with open('output2.txt', 'w') as o2:
    o2.write(output2)
如果文件有多个空行,这将失败,因为拆分将返回两个以上的部分,并尝试将它们仅分配给两个名称,
output1
output2
。可以被告知只拆分最大次数,因此更安全的说法是:

output1, output2 = contents.split('\n\n', 1)
如果有两个或多个空行,
output1
将是第一个空行之前的内容<代码>输出2将是第一个空行之后的所有内容,包括任何其他空行


当然,如果没有空行,这可能会失败。

尝试编写一些代码,如果卡住了,请将代码显示给我们。此问题中没有。可能重复。在双换行上拆分:
contents.Split('\n\n')
尝试编写一些代码,如果卡住了,向我们显示代码。此问题中没有。可能重复。在双换行上拆分:
contents.Split('\n\n')