[Python] How do I echo a variable into a file using python [closed]

Discussão em 'Python' iniciado por Stack, Fevereiro 19, 2025.

  1. Stack

    Stack Membro Participativo

    I was writing a script to go with my homemade smart home network and I came upon a problem storing variables in a file. Here is an abridged version of the code

    import datetime
    import os

    log = open('log.txt')

    def timestamp():
    errortime = ('Timestamp: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()))
    return str(errortime)

    def errormessage():
    //code

    def consolelog():
    log.write('Timestamp: ' + timestamp())
    log.write('Error Type: ' + errormessage())
    log.write('------------------')

    try:
    prit('hello')
    except:
    consolelog()
    print('done')


    The code is meant to try the code 'prit('hello') which would come back as a syntax error thus storing the variable(errortype) as Syntax Error. After this I was trying to insert a timestamp and the error type variable into a log.txt file which was returning the following error:

    log.write('Timestamp: ' + timestamp())
    can only concatenate str (not "NoneType") to str


    can anyone explain a way to input variables into a file without receiving a TypeError?

    Continue reading...

Compartilhe esta Página