Python 保存多个不同的事务示例(trans1、trans2、trans3)和#x2B;写入json
将所有事务(例如,trans1、trans2、trans3)以不同的名称和不同的金额保存到json,只要用户不断输入y,然后在另一个py程序中打开json文件以使用事务数据您的方法可行,只存在一些错误,例如标题(导入和首次打印)、打印(记录)而不是打印(trans1)等。。。您最初使用的是Python 保存多个不同的事务示例(trans1、trans2、trans3)和#x2B;写入json,python,Python,将所有事务(例如,trans1、trans2、trans3)以不同的名称和不同的金额保存到json,只要用户不断输入y,然后在另一个py程序中打开json文件以使用事务数据您的方法可行,只存在一些错误,例如标题(导入和首次打印)、打印(记录)而不是打印(trans1)等。。。您最初使用的是break,我想!='n'有点像蟒蛇 第二个请求,您需要初始化文件(在本例中,您已经完成了初始化 import datetime import json print ('--------------- Crpt
break
,我想!='n'
有点像蟒蛇
第二个请求,您需要初始化文件(在本例中,您已经完成了初始化
import datetime
import json
print ('--------------- Crptocurrency Transfer --------------- \n')
name = 'y'
while name != 'n':
# add name of the sender
print (' Enter the name of the sender: ')
sender = input("\n")
# add name of reciever #
print (' Enter the name of the receiver: ')
receiver = input("\n")
# how much would you like to send #
print (' How much would you like to send :$ ')
amount = str(input("\n"))
# save details to a log and append to text file
trans1 = [
{"sender": sender},
{"receiver": receiver},
{"amount": amount}
]
# ask if any more transactions, if no then end program
name = input (' Are there any more transactions? ( Enter y or n ): ')
with open('TransactionHistory.json', 'w') as th:
json.dump(trans1, th)
一旦文件存在并附加到循环中,就没有其他方法了,这种方法会很慢
with open('TransactionHistory.json', mode='w', encoding='utf-8') as f:
json.dump([], f)
Output,Done要将当前日期时间添加到每个事务中,json序列化有问题,它应该是
json.dump
而不是json.dumps
此代码不会按原样运行,但当我删除打印(记录)时
并在最后一行将record
替换为trans1
,一切正常,在我输入n
时终止。请按照您所说的那样将示例更新为失败。使用最新的更新,代码不会将最后一个事务转储到JSON文件,因为它会在它之前中断。您正在运行吗windows?IIRC上的此代码,windows上的输入函数不会删除“\r”(回车符)。我没有访问windows计算机进行测试的权限,但在循环结束之前添加print repr(name)
,查看它是否看起来像“n\r”。如果是,则需要执行name.rstrip()
要删除创建文件但无法打印另一个py程序内容的子例程,我尝试了json.dumps和json.load?哦…好的,您需要重写子例程以在循环中追加字典。好的,完成了。只需确保json db在追加之前已初始化即可
import json
print ('--------------- Crptocurrency Transfer --------------- ')
name = ''
with open('TransactionHistory.json', mode='r', encoding='utf-8') as feedsjson:
feeds = json.load(feedsjson)
while name != 'n':
print (' Enter the name of the sender: ')
sender = input("\n")
print (' Enter the name of the receiver: ')
receiver = input("\n")
print (' How much would you like to send :$ ')
amount = str(input("\n"))
name = input (' Are there any more transactions? ( Enter y or n ): ')
# trans1 = [
# {"sender": sender},
# {"receiver": receiver},
# {"amount": amount}
# ]
with open('TransactionHistory.json', "w") as myjson:
entry = {"sender": sender, "receiver": receiver, "amount": amount}
feeds.append(entry)
json.dump (feeds, myjson)
# Check that the json db is okay
with open('TransactionHistory.json', "r") as f:
data= json.load(f)
print ("Done\n")