我是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看到外壳
你忘了'\ n'字符! 'print'增加了换行符'write'没有。尝试在你的循环中使用'sf.write(“\ n”)' –
这个文本文件对我来说看起来是一样的,它只是没有新行或者任何分隔符来分隔数据。 – BenT
因为'print'和'write'的工作方式不同。如果你的循环已经使用了'print',那么你总是可以使用'file'参数来'print',所以'print(line.split('')[2],file = sf)' –