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

Split Text Based on Symbol into Multiple Files with Python

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

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

的新文件

我已经尝试过在另一个讨论帖 () 中发布的建议,但没有成功

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

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

拜托!下次将您遇到的错误添加到问题中!

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

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

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