2014-10-28 200 views
3

我有兩個列表寫入文本文件作爲製表符分隔列在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 
+3

我建議使用'csv'模塊。 – Kevin 2014-10-28 15:50:42

+0

Write添加一個'\ n' – 2014-10-28 15:56:19

+0

。 write()添加一個換行符。只是省略它。 – PsyKzz 2014-10-28 15:56:28

回答

9

您只需將兩個列表中的元素配對即可。你可以這樣做,使用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)格式化字符串得到一個樣樣在行。

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 ] 
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())) 
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 
相關問題