把列表放到TextFile之后line.split - Python

时间:2017-08-12 21:28:04

标签: python python-2.7

我是Python的新手,在我的MBP上使用版本2.7.13。当我运行代码打印到shell时,它会在所需列表中显示结果。但是当我写入文本文件时,结果是不同的。任何提示,指示或提示?以下是代码:

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 shell中看到的那样

1 个答案:

答案 0 :(得分: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中。 / p>