I have a text file that I would like to transpose using Python.
For example, given the following file:
asdfg
qwert
I would like the out
Setup
First lets set up our file for those of us who haven't set it up, but you can skip to the read part below, just ensure you change the filepath variable to reflect the location and name of your file:
import textwrap
# dedent removes the extra whitespace in front of each line
text = textwrap.dedent("""
asdfg
qwert""").strip() # strip takes off the first newline
filepath = '/temp/foo.txt'
with open(filepath, 'w') as writer:
writer.write(text)
Read the file
So now we have our file in place, let's read it back in to the text variable, using the with
context manager (so if we have an error, it automatically closes the file for us, and we can easily recover.):
with open(filepath, 'rU') as reader:
text = reader.read()
Manipulate the text
And here's the magic, split the lines of the text so that we have a list of two strings, expand that list into two arguments (with the *
) passed to zip
, which then goes through the strings by character pairwise, joining the pairs with an empty string, and then we print each member of that list:
list_of_strings = [''.join(chars) for chars in zip(*text.splitlines())]
for string_i in list_of_strings:
print(string_i)
should print
aq
sw
de
fr
gt