Search code examples
pythonpython-itertools

How to write itertools.izip to txt file one by line?


My code

import itertools
import os

with open("base.txt") as fv, open("new2.txt", 'r') as fi, open('sortedf.txt','w') as fs:
    vel = (line.strip() for line in fv)
    ind = (int(line.strip()) for line in fi)
    z = itertools.izip(ind, vel) # sort according to ind
    # itertools.izip(vel, ind) # sort according to vel
    for i, v in sorted(z):
        fs.write(str(v))

I got everything on one line

2.900000e+032.900000e+032.900000e+032.900000e+032.

When I change to fs.write('\n'.join(str(v)))

Then I got

2
.
9
0
0
0
0
0
e
+
0
32
.
9
0
0
0
0
0
e
+
0
32
.

How to get proper one by line value output?


Solution

  • Just Change

    for i, v in sorted(z):
        fs.write(str(v))
    

    to

    for i,v in sorted(z):
        print(v, file=fs)
    
    • \n is added automatically due to the end="\n" default parameter of print

    • works for any datatype. No need for str(v)