首页 > 解决方案 > 我想使用另一个 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()```

标签: pythonlist

解决方案


让我们假设您的所有数据都将存储在一个名为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']
           }
}

推荐阅读