【问题标题】:Split Text Based on Symbol into Multiple Files with Python使用 Python 将基于符号的文本拆分为多个文件
【发布时间】:2019-11-18 08:46:58
【问题描述】:

我有一个很长的文本文件,我想将它拆分成更小的文件。它看起来像:***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()

【问题讨论】:

  • 我也尝试使用下面显示错误的代码。 --> 请edit您的问题并添加您得到的完整错误。当您提出此类问题时,请始终这样做。

标签: split python-3.7


【解决方案1】:

请!下次添加您遇到的问题!

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

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

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

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

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

我假设您的文件如下所示:

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

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

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()! 而且我很确定您可以进一步简化它。

【讨论】:

  • 感谢您的建议。下次我一定会在消息中添加错误描述。我尝试运行上面的代码,第 5 行出现错误(for x in fo.read()...)
  • 感谢您的建议。下次我一定会在消息中添加错误描述。我尝试运行您上面建议的代码,第 5 行出现错误(for x in fo.read()...)错误描述很长,但错误描述的最后一行显示:“UnicodeDecodeError: 'utf -8' 编解码器无法解码位置 10 中的字节 0x97:无效起始字节”。如果您有任何解决此问题的建议,请告诉我。
  • 我有一个建议:在打开文件时使用正确的文件编码,另请参阅stackoverflow.com/questions/19699367/… 以及关于此错误的许多其他问题。或者如果可能的话,将您的文本文件转换为 utf-8 :)
猜你喜欢
  • 2016-06-25
  • 1970-01-01
  • 1970-01-01
  • 2014-08-24
  • 2018-06-02
  • 1970-01-01
  • 2018-04-06
  • 2013-04-22
  • 2013-09-22
相关资源
最近更新 更多