猿问

我如何将数据保存到文本文件中,主要是我在记录中写的内容

python新手,需要将此数据存储到文本文件中。主要是我的记录,但在 recsave.write 行中出现了 concat 错误(元组)。任何帮助或建议,或者只是做错了


print (' Title ')

name = 'y'


while name == 'y':


    print (' Enter the name of the sender: ')

    sender = input("\n")


     # add name of reciever #

    print (' Enter the name of the reciever: ')

    reciever = input("\n")


     # how much would you like to send # 

    print (' How much would you like to send :$ ')

    amount = input("\n")


    record = (sender, 'sent :$',amount, 'to', reciever, "\n" )


    recsave = open('Transaction History.txt', 'w')


    recsave.write(record + '\n')

    recsave.close()


    print (str(record, "\n"))


    name = input (' Are there anymore transactions? ( Enter y or n ): ')

想在打开文本文件时得到它。你得到


name 发送 $amount 给 name


还需要包括时间戳:(每次循环运行时都会将每个循环保存到记录中


人到中年有点甜
浏览 136回答 1
1回答

一只斗牛犬

创建一个包含所有信息而不是元组的字符串并写入import datetimedt = datetime.datetime.now()record = "{} : {} sent :${} to {}\n".format(dt, sender, amount, reciever)recsave = open('Transaction History.txt', 'a')recsave.write(record)recsave.close()print(record)使用模式"a"(追加)而不是"w"(写入)将新记录添加到文件中的现有记录。w将删除旧信息。在您添加的记录中,"\n"因此您不必添加它write()但是您可以创建功能来执行此操作,然后您可以在不同的地方使用它import datetimedef log(message):    dt = datetime.datetime.now()    line = "{} : {}\n".format(dt, message)    recsave = open('Transaction History.txt', 'a')    recsave.write(line)    recsave.close()    print(line)#----log("start program")record = "{} sent :${} to {}".format(dt, sender, amount, reciever)log(record)log("end program")有标准模块日志记录来创建带有历史记录的日志或文件。
随时随地看视频慕课网APP

相关分类

Python
我要回答