如何遍历csv并能够返回一步或逐行进行?

时间:2018-10-30 01:29:27

标签: python-3.x pandas csv

我正在尝试为用户查找时间。假设他们输入13(分钟),我的代码在csv中滚动并找到在时间列中具有13的每一行。然后,它一次打印出第一行。我不知道如何允许用户选择重新访问上一步?我的代码当前只是颠倒csv的顺序,从底部开始,即使这些行不是13分钟选定的行。

我是一个新手,所以请尝试解释得尽可能简单。.谢谢

请参见代码:

def time():

while True:
    find = input("Please enter a time in minutes(rounded)\n"
                "> ")

    if len(find) < 1:
        continue
    else:
        break


print("Matches will appear below\n"
      "If no matches were made\n"
      "You will return back to the previous menu.\n"
      "")

count = -1

with open("work_log1.csv", 'r') as fp:
    reader = csv.DictReader(fp, delimiter=',')
    for row in reader:
        count+=1
        if find == row["time"]:
            for key, value in row.items(): # This part iterates through csv dict with no problems
                print(key,':',value)

                changee = input("make change? ")
                if changee == "back":                    # ISSUE HERE******
                    for row in reversed(list(reader)):   # I'm trying to use this to reverse the order of whats been printed
                        for key, value in row.items():   # Unfortunately it doesnt start from the last item, it starts from
                            print(key,':',value)         # The bottom of the csv. Once I find out how to iterate through it
                                                         # Properly, then I can apply my changes
            make_change = input("make change?  or go back")

            if make_change == 'y':
                new_change = input("input new data: ")
                fp = pd.read_csv("work_log1.csv")
                fp.set_value(count, "time", new_change) # This part makes the changes to the row i'm currently on
                fp.to_csv("work_log1.csv", index=False)




        print("")

1 个答案:

答案 0 :(得分:0)

您始终可以拥有保留最后n行的列表,以便在读完新行history.pop(0)和'history.append(last_line)'后可以使用此列表返回

或者您也可以使用stream.seek函数包装此逻辑