如何逐行将itertools.izip写入txt文件?

时间:2016-04-27 12:54:25

标签: python itertools

我的代码

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))

我把所有东西放在一行

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

当我换到  fs.write('\n'.join(str(v)))

然后我得到了

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

如何逐行获取正确的值?

2 个答案:

答案 0 :(得分:2)

只需改变

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

for i,v in sorted(z):
    print(v, file=fs)
    由于\n

    end="\n"默认参数,
  • print会自动添加

  • 适用于任何数据类型。无需str(v)

答案 1 :(得分:1)

请尝试以下

fs.writelines(map(lambda x: x[1], sorted(z)))

为什么以下声明失败

fs.write('\n'.join(str(v)))

这里将v转换为列表,并在其上应用连接。为清晰起见,请查看以下示例

>>> sam = 'hello'
>>> '-'.join(sam)
'h-e-l-l-o'

那么如何使用fs.write?

  1. 写作:fs.write(v)
  2. 现在添加换行符:fs.write('\ n')
  3. 很少有建议:

    import os # load important modules first
    
    from itertools import izip # makes processing faster, if you only need izip 
    
    
    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] # use square braces
        ind = int(line.strip()) for line in fi] # use square braces
        z = izip(ind, vel) # sort according to ind
        for i, v in sorted(z):
            fs.write(v)
            fs.write('\n') # adding line break