【问题标题】:Splitting a large text file into smaller files将大文本文件拆分为小文件
【发布时间】:2018-02-07 16:08:44
【问题描述】:

我有一个大文本文件,我想将它拆分成几个不同的小文本文件。也许有人有代码?

Original file:
111
222
333
444
555
666

然后将其拆分为3个txt文件

File 1
111
222

File 2
333
444

File 3
555
666

【问题讨论】:

  • 这不是 python 建议,但如果您使用的是 linux/mac 命令行,则可以使用 split 函数。您是否专门寻找 python 解决方案?
  • 在你的情况下,也许命令 split 正在工作:split --lines=100 filename
  • 谢谢,之前查过,但不知何故错过了!

标签: bash


【解决方案1】:

如果您想将原始文件拆分为 3 个文件,而不拆分行,并将这些文件分成 file_01、file_02 和 file_03,请尝试以下操作:

split --numeric-suffixes=1 -n l/3 original_file  file_

【讨论】:

    【解决方案2】:

    使用 GNU awk:

    awk 'NR%2!=0{print >"File " ++c}; NR%2==0{print >"File " c}' original_file
    

    或更短:

    awk 'NR%2!=0{++c} {print >"File " c}' file
    

    %modulo operation

    【讨论】:

      【解决方案3】:

      编辑:最初询问pythonic解决方案的问题。

      整个网站都有类似的问题,但这里是您示例的解决方案:

      # read ('r') the file ('text.txt'), and split at each line break ('\n')
      textFile = open('text.txt','r').read().split('\n')
      
      # setup temporary array as a place holder for the files (stored as strings) to write, 
      # and a counter (i) as a pointer
      temp = ['']
      i = 0
      
      # for each index and element in textfile
      for ind,element in enumerate(textFile):
          # add the element to the placeholder
          temp[i] += element+'\n'
      
          # if the index is odd, and we are not at the end of the text file,
          # create a new string for the next file
          if ind%2 and ind<len(textFile)-1:
              temp.append('')
              i += 1
      
      # go through each index and string of the temporary array
      for ind,string in enumerate(temp):
          # write as a .txt file, named 'output'+the index of the array (output0, output1, etc.
          with open('output'+str(ind)+'.txt','w') as output:
              output.write(string)
      

      【讨论】:

        猜你喜欢
        • 2012-06-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-23
        • 1970-01-01
        • 1970-01-01
        • 2013-04-05
        相关资源
        最近更新 更多