Writing to a text file as tabs separated by columns in Python

I have two lists

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

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

      

I want the highlighted output delimited text file to look like

ATTTGTA ATTGTA
ATTTGTA AAAT
ATTTGTA TTTA

      

I tried the following piece of code, but it doesn't write o / p to two columns, just like new lines every time

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 result I am getting

ATTTGTA
    ATTGTA
ATTTGTA
    AAAT
ATTTGTA
    TTTA

      

+3


source to share


4 answers


You just need to concatenate the items in the two lists. You can do it with the function 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 also used format

(see specs ) to format the string to get all one string.

+9


source


How about something like this? This gives you 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 a parameter that the user can define the size of the interval.



To fit your example data:

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

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

lines = [ A, A_modified ]

      

+2


source


If your lists are huge, I suggest using 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


source


Apart from other great answers, as an alternative with, try/except

it will log all other items in the list if their length is different (at least in your example):

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 

      

+1


source







All Articles