在Python中写入文本文件作为制表符分隔列

时间:2014-10-28 15:47:47

标签: python

我有两个列表

A = ["ATTTGTA", "ATTTGTA", "ATTTGTA", "ATTTGTA"]

A_modified = ["ATTGTA", "AAAT", "TTTA"]

我想要一个输出标签分隔的txt文件,看起来像

ATTTGTA ATTGTA
ATTTGTA AAAT
ATTTGTA TTTA

我尝试了下面这段代码,但它没有在两列中写o / p,就像每次都有新行一样

with open ('processed_seq.txt','a') as proc_seqf:
          proc_seqf.write(A)
          proc_seqf.write("\t")
          proc_seqf.write(A_modified)

这是我得到的输出

ATTTGTA
    ATTGTA
ATTTGTA
    AAAT
ATTTGTA
    TTTA

4 个答案:

答案 0 :(得分:10)

您只需要将两个列表中的元素配对即可。您可以使用zip函数执行此操作:

with open ('processed_seq.txt','a') as proc_seqf:
    for a, am in zip(A, A_modified):
        proc_seqf.write("{}\t{}".format(a, am))

我还使用format(请参阅specs)格式化字符串以将所有内容整理为一行。

答案 1 :(得分:2)

这样的事情怎么样?它为您提供了一些输入和输出的灵活性..

lines = [
    ['a', 'e', '7', '3'],
    ['b', 'f', '1', '5'],
    ['c', 'g', '2', '10'],
    ['d', 'h', '1', '14'],
    ]

def my_print( lns, spacing = 3 ):
    widths = [max(len(value) for value in column) + spacing
              for column in zip(*lines)]
    proc_seqf = open('processed_seq.txt','a')
    for line in lns:
       pretty = ''.join('%-*s' % item for item in zip(widths, line))
       print(pretty) # debugging print
       proc_seqf.write(pretty + '\n')
    return

my_print( lines )

我添加了用户可以决定间距大小的选项..

要与您的示例数据匹配:

A = ["ATTTGTA", "ATTTGTA", "ATTTGTA", "ATTTGTA"]

A_modified = ["ATTGTA", "AAAT", "TTTA"]

lines = [ A, A_modified ]

答案 2 :(得分:1)

如果您的列表很大,我建议使用itertools.cycle()

import itertools
ac=itertools.cycle(A)
a_mc=itertools.cycle(A_modified)
with open ('processed_seq.txt','a') as proc_seqf:
    for i in A_modified:
      proc_seqf.write("{}\t{}".format(ac.next(), a_mc.next()))

答案 3 :(得分:1)

除了其他很好的答案之外,作为try/except的替代方案,如果长度不同(至少在您的样本中),它会在列表中写下所有剩余的元素:

with open ('processed_seq.txt','w') as proc_seqf:
    for each in range(max(len(A), len(A_modified))):
        try:
            proc_seqf.write("{}\t{}\n".format(A[each], A_modified[each]))
        except IndexError:
            if len(A) > len(A_modified):
                proc_seqf.write("{}\t\n".format(A[each]))
            else:
                proc_seqf.write("\t{}\n".format(A_modified[each]))

cat processed_seq.txt
ATTTGTA ATTGTA
ATTTGTA AAAT
ATTTGTA TTTA
ATTTGTA