0

say the file has the following content:

Xkr4    0   0   0   0
Gm1992  0   0   0   0
Gm37381 0   0   0   0
Rp1 0   0   0   0
Rp1.1   0   0   0   0
Sox17   0   0   0   0
f=open(tsv_path, 'r')
transposed_iterator = zip(*csv.reader(open(tsv_path), delimiter = '\t'))
with open(output_tsv_path, 'w') as out:
    for row in transposed_iterator:
        out.write(delimiter.join(row) + '\n')

Result:

Xkr4    Gm1992  Gm37381 Rp1 Rp1.1   Sox17
0   0   0   0   0   0
0   0   0   0   0   0
0   0   0   0   0   0
0   0   0   0   0   0

The above lines exactly do what I want but the problem is I am using very old jython which doesn't contain csv module. How can I do it without csv module?

money
  • 11
  • 2

1 Answers1

1

You can try this out:

f=open('text.txt')
lines = (line.strip().split() for line in list(f))

with open('otext.txt', 'a') as fo:
    for line in zip(*lines):
        print(*line, sep = '\t', file = fo)

f.close()
Sayandip Dutta
  • 15,602
  • 4
  • 23
  • 52
  • the file can be very huge, so I can't store it in memory in the form of a list. This is the reason I used csv.reader which return an iterator – money Jan 09 '20 at 09:21
  • `lines = (line.strip().split() for line in list(f))` this line returns an iterator as well. It won't load the entire file in memory. It will generate the lines lazily. See [How exactly does a generator comprehension work?](https://stackoverflow.com/q/364802/5431791) – Sayandip Dutta Jan 09 '20 at 09:23
  • thanks @Sayandip, I understood but it is skipping the last column. And as I said the jython version is very old, it doesn't support 'yield' keyword. – money Jan 10 '20 at 04:36