无法在python中

时间:2018-01-21 16:54:21

标签: python python-3.x python-3.6

我正在尝试创建一个python脚本来存储生日日期并将其存储在文本文件中,而不重复相同的名称和出生日期,但我无法做到。我正在使用python 3.6。我能够写但无法检索它。我想要一只手解决这个问题。

Birthday = {}

with open('Birthday.txt', 'r') as file:  # opening txt file in read mode since it doesn't support in append mode

file.seek(0)
content = file.readlines()

while True:
    name = input('Enter name:')  # asking for name
    if name in Birthday:
        birth_day = Birthday[name] + 'is a birthday of' + name + '.' + '\n'
        print(birth_day)

        with open('Birthday.txt', 'a') as f:  # Checking if it already in file or not
            for lines in content:
                if birth_day in content:
                    print(birth_day)
            f.close()

    else:
        print('There is no such name in database')
        print('Do you want to add it on database?')
        choice = input('')
        if choice == 'y':  # if not in file than append upon it
            new_dates = input('What\'t is the birthday of '+name+'?')
            Birthday[name] = new_dates
            new_birthdates = Birthday[name] + 'is a birthday of' + name + '.' + '\n'
            print(new_birthdates)

            with open('Birthday.txt', 'a') as fi:
                fi.write(new_birthdates)
                fi.close()

1 个答案:

答案 0 :(得分:0)

当您写入文件时,请尝试使用'w'而不是a。作为一种手段,您想要在使用写入功能的地方附加。