2017-08-12 60 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