2016-01-14 75 views
2

我有(在一個單獨的行中的每個條件)具有以下信息的文本文件的多個列表:保存在單個文本文件

UP_aic up 920.5 4 17280.0 down 17764.5 2 28186.5 up 28249.1 
DOWN_aic down 941.0 2 8800.5 up 8894.3 down 11691.0 2 20316.2 up 
20363.1 4 26901.8 down 26901.8 
UP_adc down 1477.1 
DOWN_adc up 1752.8 

我已經實現了代碼,以除去2S和4S和它們各自的定時(見下文),我想要的是將這些信息保存在另一個文本文件中!

但是,今天上午我只設法保存最後一行(DOWN_adc up 1752.8):正常,垂直而不是水平,所有字符「粘」在一起等等。

所以我現在保留了最基本的寫入方法。我知道所有以前的行都會被下一行刪除,所以只有最後一行保留,但我無法弄清楚如何防止這種情況。

下面是代碼:

from sys import argv 
from itertools import tee, islice, chain, izip 
script, from_file, to_file = argv 
print "Here's your file %r:" %from_file 

fhand=open(from_file) 
total = 0 
for line in fhand: 
    words=line.split() 
    def previous_and_next(some_iterable): 
     items, nexts = tee(some_iterable, 2) 
     nexts = chain(islice(nexts, 1, None), [None]) 
     return izip(items, nexts) 
    for item, nxt in previous_and_next(words): 
     if item=='2': 
      words.remove(item) 
      words.remove(nxt) 
     elif item=='4': 
      words.remove(item) 
      words.remove(nxt) 
    print words 

with open(to_file, 'w') as output:   
     output.write(str(words)+'\n') 

fhand.close() 
output.close() 

那麼,如何保存在單獨的行這樣的數據再次各種條件(尖括號,逗號等都是沒有問題的)?

['UP_aic', 'up', '920.5', 'down', '17764.5', 'up', '28249.1'] 
['DOWN_aic', 'down', '941.0', 'up', '8894.3', 'down', '11691.0', 'up', '20363.1', 'down', '26901.8'] 
['UP_adc', 'down', '1477.1'] 
['DOWN_adc', 'up', '1752.8'] 
+1

你的意思是['str.join()'](https://docs.python.org/3/library/stdtypes.html#str.join)? –

+0

您確定要「打印單詞」而不是將每個單詞附加到「列表」,然後您可以循環並寫入文件? – TigerhawkT3

+0

TigerhawkT3 - 可以刪除打印語句,我只是想知道我的代碼是否符合我的要求。 Kevin,str.join()對列表不起作用... – monechka

回答

0

write()的調用是for循環之外,因此words只寫入文件的循環結束後。到那時,它包含了最後一行讀的內容。

你的代碼更改爲類似

def previous_and_next(some_iterable): 
    items, nexts = tee(some_iterable, 2) 
    nexts = chain(islice(nexts, 1, None), [None]) 
    return izip(items, nexts) 

with open(to_file, 'w') as output:  
    for line in fhand: 
     words = line.split() 
     for item, nxt in previous_and_next(words): 
      if item == '2': 
       words.remove(item) 
       words.remove(nxt) 
      elif item == '4': 
       words.remove(item) 
       words.remove(nxt) 
     print words 
     output.write(str(words)+'\n') 

不需要調用output.close(),這就是with塊是什麼。