How to save output from python like tsv

前端 未结 5 1198
没有蜡笔的小新
没有蜡笔的小新 2021-01-02 02:10

I am using biopython package and I would like to save result like tsv file. This output from print to tsv.

for record in SeqIO.parse(\"/home/fil/Desktop/420_         


        
5条回答
  •  萌比男神i
    2021-01-02 03:10

    My preferred solution is to use the CSV module. It's a standard module, so:

    • Somebody else has already done all the heavy lifting.
    • It allows you to leverage all the functionality of the CSV module.
    • You can be fairly confident it will function as expected (not always the case when I write it myself).
    • You're not going to have to reinvent the wheel, either when you write the file or when you read it back in on the other end (I don't know your record format, but if one of your records contains a TAB, CSV will escape it correctly for you).
    • It will be easier to support when the next person has to go in to update the code 5 years after you've left the company.

    The following code snippet should do the trick for you:

    #! /bin/env python3
    import csv
    with open('records.tsv', 'w') as tsvfile:
        writer = csv.writer(tsvfile, delimiter='\t', newline='\n')
        for record in SeqIO.parse("/home/fil/Desktop/420_2_03_074.fastq", "fastq"):
            writer.writerow([record.id, record.seq, record.format("qual")])
    

    Note that this is for Python 3.x. If you're using 2.x, the open and writer = ... will be slightly different.

提交回复
热议问题