python - 我想使用另一个 python 文件上的代码在一个单独的文件上创建赛车手的时间列表
问题描述
enter code here
基本上,我希望能够拥有 2 个不同的文件,一个带有代码,一个带有时间。每次我输入跑步者的名字时,我都希望它
A. 创建新名称和时间 像这样:
runner1 = [23:43:15, 18:14:16]
或者
B. 更新跑步者信息并为其添加时间 像这样:
runner1 = [23:43:15, 18:14:16] but add 19:16:18 to it
但我真的需要它保存到另一个文件,所以即使我关闭程序,它仍然会保存。一切都需要更新,不应创建新列表(除非它不存在)
任何帮助都将不胜感激,因为我为此失去了无数小时的睡眠!这是我已经拥有的代码:
Racename = input("Name of the race")
runnerstxt = open("runners.py", "a")
runnerstxt.write(Racename + '\n')
while True:
runnernameandtime = []
runnerName = input("What was the racer's name? ")
runnernameandtime.append(runnerName)
runnerTime = input("What was the racer's time? ")
runnernameandtime.append(runnerTime)
runnerstxt.write(str(runnernameandtime))
runnerstxt.write("\n")
runnernameandtime.clear()```
解决方案
让我们假设您的所有数据都将存储在一个名为race_data.pickle
. 我们将所有数据存储在一个字典中,然后可以访问之前存储的所有内容。
import pickle
# Check if a file exists
try:
# Previous file found, loading it
race_data = pickle.load(open("race_data.pickle", "rb"))
except (OSError, IOError) as e:
race_data = {}
Racename = input("Name of the race")
#Check if the race has previously been registered
if Racename not in race_data.keys():
#Add if not registered
race_data[Racename] = {}
while True:
runnerName = input("What was the racer's name? ")
#Check if the runner has been registered
if runnerName not in race_data[Racename].keys():
#Add empty if not registered
race_data[Racename][runnerName] = []
#Add the runner's time in the list
runnerTime = input("What was the racer's time? ")
race_data[Racename][runnerName].append(runnerTime)
#Save the latest data into the pickle
with open("race_data.pickle", "wb") as f:
pickle.dump(race_data, f)
您可以随时终止该程序,它将具有上次存储对象时的数据。数据将如何存储的示例如下:
{
'Race1': {
'Racer1': ['3', '10'],
'Racer2': ['5', '22'],
'Racer3': ['20']
},
'Race2': {
'Racer4': ['10'],
'Racer1': ['20'],
'Racer10': ['44']
}
}
推荐阅读
- r - 每年一个闪避的条形图
- node.js - 在反应js中加载期间播放音频文件
- node.js - NodeJS:上传前保存文件
- function - 什么编程语言在函数的参数“内部”和“之后”有冒号
- spring-boot - Pod 进入崩溃返回循环
- r - 在 R 中的预测函数中获取空数据错误
- angular - 从 tslint 切换到 eslint 后,Angular 12 模板 linting 不起作用
- javascript - 对如何在来自 javascript 的 C# .NET 中实现 HMACSHA1 感到困惑
- django - AttributeError:此方法仅适用于类,不适用于实例。Django 视图集
- typescript - Typescript unfold object type