如何使用python将文本文件拆分为多个文本文件

时间:2013-03-21 21:37:33

标签: python python-2.7

我有一个巨大的文本文件,其数据集如下

EOG61ZHH8   ENSRNOG00000004762  627
EOG61ZHH8   ENSRNOG00000004762  627
EOG61ZHH9   ENSG00000249709 1075
EOG61ZHH9   ENSG00000249709 230
EOG61ZHH9   ENSG00000249709 87
EOG61ZHHB   ENSG00000134030 2347
EOG61ZHHB   ENSG00000134030 3658
EOG61ZHHB   ENSRNOG00000018342  241
EOG61ZHHB   ENSRNOG00000018342  241
EOG61ZHHC   ENSBTAG00000006084  1159
EOG61ZHHC   ENSG00000158828 820
EOG61ZHHC   ENSMMUG00000000126  631

我希望像这样转换或拆分

EOG61ZHH8.txt
ENSRNOG00000004762  627
ENSRNOG00000004762  627
EOG61ZHH9.txt
ENSG00000249709 1075
ENSG00000249709 230
ENSG00000249709 87

等等。我不知道从哪里开始从上面的文本文件中获取新的txt文件,我之前做过这个事情,但条目在开始之前有'['符号,现在我有很多文件,但没有任何特殊标志来转换它们 这是我在python中完成的代码

with open("entry.txt") as f: 
  for line in f:
    if line[0] == "[":
     if out: out.close()
     out = open(line.split()[1] + ".txt", "w")
   else: out.write(line)'

我在windows中使用它,所以我知道linux awk命令,所以请不要关于linux的信息

2 个答案:

答案 0 :(得分:1)

您只需对脚本进行一些调整即可:

out = None
oldfile = None
with open("entry.txt") as f: 
    for line in f:
        newfile = l.split("\t")[0]
        if newfile != oldfile:
            if out: out.close()
            out = open(newfile + ".txt", "w")
            oldfile = newfile
        out.write("\t".join(line.split("\t")[1:]))

答案 1 :(得分:0)

使用正则表达式;

import re

string = '    EOG61ZHH8   ENSRNOG00000004762  627    EOG61ZHH8   ENSRNOG00000004762  627    EOG61ZHH9   ENSG00000249709 1075    EOG61ZHH9   ENSG00000249709 230    EOG61ZHH9   ENSG00000249709 87    EOG61ZHHB   ENSG00000134030 2347    EOG61ZHHB   ENSG00000134030 3658    EOG61ZHHB   ENSRNOG00000018342  241    EOG61ZHHB   ENSRNOG00000018342  241    EOG61ZHHC   ENSBTAG00000006084  1159    EOG61ZHHC   ENSG00000158828 820    EOG61ZHHC   ENSMMUG00000000126  631'

result = re.findall('\s+(.*?)\s+(.*?)\s+(\d+)', string, re.S)

buffer = {}

for i in result:
    if not i[0] in buffer:
        buffer[i[0]] = ''

    buffer[i[0]] = buffer[i[0]] + i[1] + '  ' + i[2] + '\n'

for i in buffer.iteritems():
    print i

    filename = i[0] + '.txt'
    content = i[1] # you could remove the unneeded "\n" here with substring if wanted

    # CODE: Create the file with "filename"

    # CODE: Write "content" to the file