在.txt fi中按时间排序行

2024-06-10 01:41:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个编程行乞者,我决定尝试用Python3.8编写一个程序来学习它。。进展是缓慢的,但有益的是,我在这个网站上找到了很多答案,所以我继续前进。但是我发现了一个我找不到答案的问题,所以我希望有人能帮助我。 我的程序是为了存储结果从田径赛道。用户将结果输入到空文件中,然后按某种方式排序,即先显示某个规程中的最佳结果,然后再显示第二个最佳结果。。。除了时间,输入还需要日期和地点。因此.txt文件中的最终输出如下所示:

100m #the discipline

  1. 9;99 01.01.2019 London #delimiter is \t

  2. 10;00 02.01.2019 New York

Halfmarathon #second discipline

  1. 59:59;99 21.09.2019 Berlin

  2. 1:00:00;01 23.04.2019 Boston

时间格式为小时:分钟:秒;百分之一秒,如果小时和分钟为0,则不显示(如100米或半程马拉松中的小时)。你知道吗

现在我正在升级程序;我正在尝试将结果插入到已经编写的文件中。所以,假设运动员今天在半程马拉松上跑了1个小时,我想把这个结果插入到文件中,如下所示:

100m #the discipline

  1. 9;99 01.01.2019 London #delimiter is \t

  2. 10;00 02.01.2019 New York

Halfmarathon #second discipline

  1. 59:59;99 21.09.2019 Berlin
  2. 1:00:00;00 21.11.2019 StackOverflow
  3. 1:00:00;01 23.04.2019 Boston

所以我需要把结果插入2。参加半程马拉松训练。我知道如何找到正确的规程(所以半程马拉松)以及如何显示规程中的所有结果,但我不知道如何提取结果,输入新结果,然后对所有结果进行排序。你知道吗

所以总结一下,我需要一些关于这个问题的总体思路,而不是确切的代码。这是我目前的代码:

    import csv

with open('test.txt', 'r+') as csv_file:
    csv_reader =csv.reader(csv_file, delimiter='\t')

    a = '600 m' #discipline
    found = False #searching if our discipline is in the file
    for line in csv_reader:
        if line == [a]:
            found = True
            for line in csv_reader:
                lenght = len(line)
                if lenght < 4: #result have lenght of 4 (place, result, date, location), when lenght is shorter, that means that there are no more results in this dsicipline
                    csv_writer = csv.writer(csv_file, delimiter='\t')
                    input = input('Input something: ') #trying to write something to the last line of this discipline, I was trying to see if this works
                    csv_writer.writerow([vnos])
                    break #break
                else:
                    print(line) # printing the results

Tags: 文件csvthein程序ifisline