As already mentioned in the other answer the right tool for transposing the text will be not a dictionary but a list of lists which can then be easily transposed using Pythons zip()
method.
Below the complete code for reading the data from file, transposing them using the function txt_T(txt_IN)
which returns the transposed txt_OUT
, and for writing txt_OUT
to the output file.
With the option verbose=True
you can follow the single steps required to achieve the result yourself again if you like (the output for the case in question is provided after the code).
txt_T(txt_IN, sep=3*" ", CRLF='\n')
allows to specify the separator between the table entries (e.g. change it to '\t'
as used in your code) and the line end (on Windows change to CRLF='\r\n'
):
mln_IN = """\
A a
B b
C c
D d
E e"""
with open('transposeText_mln_IN.txt','w') as fw:
fw.write(mln_IN)
# Expected output:
mln_OUT = """\
A B C D E
a b c d e"""
# Code:
def txt_T(txt_IN, sep=3*" ", CRLF='\n', verbose=False):
verb_sep = '\n----------------\n'
""" Transpose columns to lines in a table provided as txt_IN e.g.:
A a
B b
C c
and return txt_OUT of the transposed table e.g.:
A B C
a b c """
L = []
if verbose: print(txt_IN, end=verb_sep)
for line in txt_IN.split(CRLF):
if verbose: print( line, line.split(sep) )
L.append(line.split())
if verbose: print(verb_sep[1:], end='')
if verbose: print(L, end='\n---\n')
if verbose: print( [ list(item) for item in zip(*L) ], end=verb_sep)
txt_OUT = CRLF.join([sep.join(list(item)) for item in zip(*L)])
if verbose: print(txt_OUT)
return txt_OUT
# ---
with open('transposeText_mln_IN.txt','r') as fr:
txt_IN = fr.read()
# assert txt_IN == mln_IN # for code test purposes
sep = 3*" "
CRLF='\n'
txt_OUT = txt_T(txt_IN, sep=sep, CRLF=CRLF)
# assert txt_OUT == mln_OUT # for code test purposes
with open('transposeText_mln_OUT.txt','w') as fw:
fw.write(txt_OUT)
gives with verbose=True
:
A a
B b
C c
D d
E e
----------------
A a ['A', 'a']
B b ['B', 'b']
C c ['C', 'c']
D d ['D', 'd']
E e ['E', 'e']
----------------
[['A', 'a'], ['B', 'b'], ['C', 'c'], ['D', 'd'], ['E', 'e']]
---
[['A', 'B', 'C', 'D', 'E'], ['a', 'b', 'c', 'd', 'e']]
----------------
A B C D E
a b c d e