I'm new to scripting. I have a table (Table1.txt) and I need to create another table that has Table1's rows arranged in columns and vice versa. I have found solutions to this problem for Perl and SQL but not for Python.
I just started learning Python two days ago, so this is as far as I got:
import csv
import sys
with open(sys.argv[1], "rt") as inputfile:
readinput = csv.reader(inputfile, delimiter='\t')
with open("output.csv", 'wt') as outputfile:
writer = csv.writer(outputfile, delimiter="\t")
for row in readinput:
values = [row[0], row[1], row[2], row[3]]
writer.writerow([values])
This just reproduces the columns as columns. What I would have liked to do now is to write the last line as writer.writecol([values]) but it seems that there is no command like that and I haven't found another way of writing rows as columns.
解决方案
The solution in general to transpose a sequence of iterables is: zip(*original_list)
sample input:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
program:
with open('in.txt') as f:
lis = [x.split() for x in f]
for x in zip(*lis):
for y in x:
print(y+'\t', end='')
print('\n')
output:
1 6 11
2 7 12
3 8 13
4 9 14
5 10 15