2016-04-27 74 views
0

我的代碼如何將itertools.izip逐行寫入txt文件?

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

你想在每行之後換行,對不對?那麼'fs.write(str(v)+'\ n')'怎麼樣? –

+0

@GarethMcCaughan是的,這是賴特的格式。 –

回答

2

只是改變

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

to

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

  • 適用於任何數據類型的end="\n"默認參數自動添加。不需要str(v)

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

幾點建議:

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