Python如果定义了函数,将变量输出写入文件的方法是什么?

时间:2018-05-27 08:10:04

标签: python python-3.5

如果定义了函数,如何在文件中写入变量数据信息。 虽然我尝试了以下方法,但它只写了几行:

请让我知道我在这里做的错误......

fileData = 'ldap_conn_logs'
def ChkCon():
    Flag    = False
    FlagTcp = False
    NewStr  = ''
    OutStr  = ''
    HOST    = ''
    MARKER  = '----------------'
    NEWLINE = '\n'
    with open('ldap_bind_netstat', 'r') as log:
        for line in log:
            if '| SUCCESS |' in line:
                if Flag:
                    return HOST
                    return MARKER
                    return NewStr
            if '| SUCCESS |' in line:
                Flag = False
                FlagTcp = True
                HOST = line.split()[0]
                NewStr = ''
            elif 'FAILED' in line:
                FlagTcp = False
            elif 'UNREACHABLE' in line:
                FlagTcp = False
            if FlagTcp and line.startswith('tcp'):
                NewStr += line
                if 'tsdj-lb-oidc01' not in line:
                    Flag = True
                OutStr = HOST + NEWLINE + MARKER + NEWLINE + NewStr
                fileWrite = open(fileData, mode='a', encoding='utf-8')
                fileWrite.write(OutStr)
                fileWrite.close()
ChkCon()

2 个答案:

答案 0 :(得分:1)

正如文尼提到的,这个例子既不完整也不可证实。我最好的猜测是,您希望将mode='w+'替换为mode='a'。你似乎没有真正阅读fileData,所以不要为+而烦恼。每次运行循环时,写入模式都会覆盖您的文件。

答案 1 :(得分:0)

@reculseSoul,使用str.format方法并关闭for循环外的fileWrite.close()。请尝试以下它应该工作。

def ChkCon():
    Flag    = False
    FlagTcp = False
    NewStr  = ''
    OutStr  = ''
    HOST    = ''
    MARKER  = '----------------'
    NEWLINE = '\n'
    fileData = 'ldap_conn_logs'
    with open('ldap_bind_netstat', 'r') as log:
        for line in log:
            if '| SUCCESS |' in line:
                if Flag:
                    return HOST
                    return MARKER
                    return NewStr
            if '| SUCCESS |' in line:
                Flag = False
                FlagTcp = True
                HOST = line.split()[0]
                NewStr = ''
            elif 'FAILED' in line:
                FlagTcp = False
            elif 'UNREACHABLE' in line:
                FlagTcp = False
            if FlagTcp and line.startswith('tcp'):
                NewStr += line
                if 'tsdj-lb-oidc01' not in line:
                    Flag = True
                OutStr = HOST + NEWLINE + MARKER + NEWLINE + NewStr
                fileWrite = open(fileData, 'w')
                fileWrite.write(OutStr)
                file.write('{0}'.format(OutStr))
        fileWrite.close()
        log.close()
ChkCon()