如何将包含两列的文本文件转换为fasta格式

时间:2017-09-13 21:48:06

标签: python

我对这段代码感到困惑。我有testfile.txt

Sclsc1_3349_SS1G_09805T0        TTGCGATCTATGCCGACGTTCCA
Sclsc1_8695_SS1G_14118T0        ATGGTTTCGGC
Sclsc1_12154_SS1G_05183T0       ATGGTTTCGGC
Sclsc1_317_SS1G_00317T0         ATGGTTTCGGC
Sclsc1_10094_SS1G_03122T0       ATGGTTTCGGC

我想将此文件转换为以下格式(fasta):

>Sclsc1_3349_SS1G_09805T0
TTGCGATCTATGCCGACGTTCCA
>Sclsc1_8695_SS1G_14118T0
ATGGTTTCGGC
>Sclsc1_12154_SS1G_05183T0
ATGGTTTCGGC
>Sclsc1_317_SS1G_00317T0
ATGGTTTCGGC
>Sclsc1_10094_SS1G_03122T0
ATGGTTTCGGC

这是我的python代码(运行它像:python mycode.py testfile.txt outputfile.txt,但它不会输出我想要的结果。有人可以帮我纠正这段代码吗?谢谢!

import sys

#File input
fileInput = open(sys.argv[1], "r")

#File output
fileOutput = open(sys.argv[2], "w")

#Seq count
count = 1 ;

#Loop through each line in the input file
print "Converting to FASTA..."
for strLine in fileInput:

    #Strip the endline character from each input line
    strLine = strLine.rstrip("\n")

    #Output the header
    fileOutput.write("> " + str(count) + "\n")
    fileOutput.write(strLine + "\n")

    count = count + 1
print ("Done.")

#Close the input and output file
fileInput.close()
fileOutput.close()

2 个答案:

答案 0 :(得分:1)

正如您使用的是Linux操作系统,这里简短而快速 awk 单行:

awk '{ printf ">%s\n%s\n",$1,$2 }' testfile.txt > outputfile.txt

outputfile.txt内容:

>Sclsc1_3349_SS1G_09805T0
TTGCGATCTATGCCGACGTTCCA
>Sclsc1_8695_SS1G_14118T0
ATGGTTTCGGC
>Sclsc1_12154_SS1G_05183T0
ATGGTTTCGGC
>Sclsc1_317_SS1G_00317T0
ATGGTTTCGGC
>Sclsc1_10094_SS1G_03122T0
ATGGTTTCGGC

答案 1 :(得分:0)

import sys
inp = open('Dataset.csv', "r")
outp = open('Book1.txt', "w")


print ("Convertion")
for a in inp:
    a = a.rstrip("\n")

    outp.write("> " + strLine[0:6] + "\n")
    outp.write(strLine[11:-4] + "\n")



print ("Done")

inp.close()
outp.close()