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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26612638/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:45:25  来源:igfitidea点击:

Writing into text file as tab separated columns in Python

python

提问by Ssank

I have two lists

我有两个清单

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

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

I want an output tab separated txt file looking like

我想要一个输出制表符分隔的 txt 文件,看起来像

ATTTGTA ATTGTA
ATTTGTA AAAT
ATTTGTA TTTA

I tried the following piece of code but it does not write o/p in two columns, just as new rows each time

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

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

This is the output I get

这是我得到的输出

ATTTGTA
    ATTGTA
ATTTGTA
    AAAT
ATTTGTA
    TTTA

采纳答案by Mihai Maruseac

You just need to pair the elements in the two list. You can do that using the zipfunction:

您只需要将两个列表中的元素配对即可。您可以使用以下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))

I have also used format(see specs) to format the string to get everything in a single line.

我还使用format(参见规范)来格式化字符串以将所有内容都放在一行中。

回答by gmas80

What about something like this? It provides you with some flexibility in input and output..

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

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 )

I added the option that the user can decide the size of the spacing..

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

To match with your example data:

要与您的示例数据匹配:

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

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

lines = [ A, A_modified ]

回答by Kasramvd

If your lists are huge ,i suggest use itertools.cycle():

如果您的列表很大,我建议使用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()))

回答by Anzel

Apart from other great answers, as an alternative with try/exceptit will write all remaining elements in the list if their lengths are different (at least in your sample):

除了其他很棒的答案之外,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