使用Python将基于符号的文本拆分为多个文件

我有一个非常长的文本文件,我想将其拆分为较小的文件。看起来像:*** 200302 abcdfg *** 200303 fasafafd *** 200304 dajhskjsd

我希望将***之间的内容另存为(1.txt,2.txt,3.txt ...)类型的新文件

我尝试了另一个讨论线程(How can I split a text file into multiple text files using python?)中发布的建议

我还尝试使用下面显示错误的代码。错误在第6行(SyntaxError:行继续符后出现意外字符)。

with open ('filename.txt','r') as fo:

    op=''
    start=0
    cntr=1
    for x in fo.read().split(*\n*):
        if (x=='***'):
            if (start==1):
                with open (str(cntr)+'.txt','w') as opf:
                    opf.write(op)
                    opf.close()
                    op=''
                    cntr+==1
            else:
                start=1

        else:
            if (op==''):
                op = x
            else:
                op=op + '\n' + x

    fo.close()
gongyannn 回答:使用Python将基于符号的文本拆分为多个文件

请!下次添加您遇到的错误!

首先,您的代码中有两个语法错误:

for x in fo.read().split(*\n*): # It's not *\n* but '\n'!

cntr+==1 # It's += !

当您仔细阅读错误消息时,这些很容易发现!

修复这些错误后,您的代码将运行,但将省略文件的最后一行!

我认为您的文件如下所示:

***  
200302 abcdfg 
***  
200303 fasafafd  
***
200304 dajhskjsd 

所以也要获得最后一行,只需在末尾添加一个if(顺便说一句:在这样简单的ifs中不需要括号):

with open ('filename.txt','r') as fo:

    op=''
    start=0
    cntr=1
    for x in fo.read().split("\n"):
        if x=='***':
            if start==1:
                with open (str(cntr)+'.txt','w') as opf:
                    opf.write(op)
                    opf.close()
                    op=''
                    cntr+=1
            else:
                start=1

        else:
            if not op:
                op = x
            else:
                op=op + '\n' + x

    if start == 1 and op:
        with open (str(cntr)+'.txt','w') as opf:
            opf.write(op)
            opf.close()
            op=''
            cntr+=1


    fo.close()

这也可以简化为

with open ('filename.txt','r') as fo:

    start=1
    cntr=0
    for x in fo.read().split("\n"):
        if x=='***':
            start = 1
            cntr += 1
            continue
        with open (str(cntr)+'.txt','a+') as opf:
            if not start:
                x = '\n'+x
            opf.write(x)
            start = 0

使用.close()时不需要with! 而且我很确定您可以进一步简化此操作。

本文链接:https://www.f2er.com/3096674.html

大家都在问