如何使用 python 将变量回显到文件中

How do I echo a variable into a file using python

我正在编写一个脚本来配合我的自制智能家居网络,但我遇到了在文件中存储变量的问题。这是代码的简化版本

import datetime
import os

log = open('log.txt')

def timestamp():
    errortime = ('Timestamp: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()))
    print(errortime)
    errortime = 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')

该代码旨在尝试代码 'prit('hello') ,它会作为语法错误返回,因此将变量(错误类型)存储为语法错误。在此之后,我试图将时间戳和错误类型变量插入到返回以下错误的 log.txt 文件中:

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

谁能解释一种将变量输入文件而不会收到 TypeError 的方法?

timestamp() 不应该自己打印,它应该只是 return 字符串。

您还需要使用 datetime.strftime(),而不是普通的字符串格式。

def timestamp():
    return datetime.datetime.now().strftime('Timestamp: {:%Y-%m-%d %H:%M:%S}')
import datetime
import os

log = open('log.txt', 'w')


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


def errormessage(e):
    errortype = ''
    if isinstance(e, OSError):
        errortype = ('OSError')
    elif isinstance(e, SyntaxError):
        errortype = ('SyntaxError')
    elif isinstance(e, AssertionError):
        errortype = ('AssertionError')
    elif isinstance(e, NameError):
        errortype = 'NameError'

    return errortype


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


try:
    prit('hello')
except Exception as e:
    consolelog(e)
    print('done')

首先,当打开一个文件时,您应该确定您正在使用该文件的模式:

log = open('log.txt', 'w')

这里'w'用来表示如果文件已经存在就清除,如果不存在就创建,然后从头开始写入。否则,如果我们想保留当前文件并将新数据追加到末尾,我们应该使用 'a'(追加)模式。

另一件需要注意的重要事情是,您需要在完成更改后关闭文件,这样您的更改才会被保存;因此,在 log.write() 之后,您需要添加 log.close() .

您得到的错误是因为时间戳函数没有 return 任何东西(实际上它 return NULL)。当您使用 'Timestamp: ' + timestamp() 时,您想要的是 timestamp() return 当前时间戳。但是在时间戳函数中打印错误时间并不能解决问题;您需要通过将 return errortime 添加到函数底部来 return 函数中的错误时间变量。