2017-08-12 38 views
-1

我是Python新手,在我的MBP上使用2.7.13版本。當我運行代碼打印到shell時,它將結果顯示在所需的列表中。但是當我寫入文本文件時,結果是不同的。任何提示,指針或提示?下面是代碼:將列表放入textFile之後line.split - Python

import os 
import re 

filePath = "./ssh.log.txt" 
fd = open(filePath, 'r') 
writeFile = "./origin.txt" 
sf = open(writeFile, "w") 
sf.write("[scan origin hosts]") 
#print "[scan origin hosts]" 

with fd as reader : 
    for line in reader : 
     if "success" in line: 
      sf.write (line.split(' ')[2]) 
      #print (line.split(' ')[2]) 

輸出到文本文件應該是它是如何在Python看到外殼

+2

你忘了'\ n'字符! 'print'增加了換行符'write'沒有。嘗試在你的循環中使用'sf.write(「\ n」)' –

+1

這個文本文件對我來說看起來是一樣的,它只是沒有新行或者任何分隔符來分隔數據。 – BenT

+1

因爲'print'和'write'的工作方式不同。如果你的循環已經使用了'print',那麼你總是可以使用'file'參數來'print',所以'print(line.split('')[2],file = sf)' –

回答

0

這不是太硬,只是改變

with fd as reader : 
for line in reader : 
    if "success" in line: 
     sf.write (line.split(' ')[2]) 
     #print (line.split(' ')[2]) 

with fd as reader : 
for line in reader : 
    if "success" in line: 
     sf.write (line.split(' ')[2]+"\n") 
     #print (line.split(' ')[2]) 

這個錯誤是由於write函數將字符串的確切內容輸出到文件,而python的print函數在將字符串打印到shell之前在字符串的末尾添加了換行符。

+0

我在劇本和中提琴中加入了「\ n」!這就是訣竅! – James

+0

我很高興它幫助 – Superman

+0

如果有幫助,你能接受我的答案嗎? – Superman