【问题标题】:Why do my dictionaries not update after I close the program?为什么我关闭程序后我的字典没有更新?
【发布时间】:2020-11-11 13:19:23
【问题描述】:

我正在尝试创建一个程序,将酒店房间号分配给客人。分配后,在字典中,键的值应更新为“不可用”或“保留”。但是,问题是,在我关闭程序之后。那些已更新的房间号将重新变为“可用”。

有没有办法改变这个值,即使在我关闭程序后它也会保持更新?

import math
f = open('room.txt',  'r+')
#Hotel Rooms
for i in range(1, 7):
    locals()['Level{}'.format(i)] = {} # Creating Dictionary

start = 101
for x in range(1, 7):
    for i in range(start, start + 10):
        eval("Level" + str(x))[i] = 'Available' # Adding Values into Dictionary
    start += 100

# heading function
def heading(number, header):
    for i in range(60):
        print('-', end = '')
    print()
    for i in range(number):
        print('*', end = ' ')
    print('\n' + header)
    for i in range(number):
        print('*', end = ' ')
    print()

# customer details function
def customer():
    print('''Room Types:
1 --> Single (Level 1)
2 --> Double (Level 2)
3 --> Triple (Level 3)
4 --> Quad   (Level 4)
5 --> Queen  (Level 5)
6 --> King   (Level 6)
''')
    room = input('Room Type: ')
    name = input('Name: ')
    hp = input('Mobile Number: ')
    guests = input('Number of Guests: ')
    arrival = input('Arrival Date(dd/mm/yyyy): ')
    departure = input('Departure Date(dd/mm/yyyy): ')
    confirm = input('Confirmation(Y/N): ')
    conf(confirm, room, option)
    
# confirmation function + room for guest
def conf(con, num, opt):
    if con == 'Y':
        try:
            for level, availability in eval('Level' + str(num)).items():
                if availability == 'Available':
                    print('Guest Room Number:', level)
                    if option == '1':
                        eval('Level' + str(num))[level] = 'Reserved'
                    elif option == '2':
                        eval('Level' + str(num))[level] = 'Unavailable'
                    print('\nRoom Recorded!')
                    break
            for i in range(1, 7):
                f.write('Level ' + str(i) + '\n')
                for key in eval('Level' + str(i)):
                    f.write(str(key) + ": " + eval('Level' + str(i))[key] + '\n')
                f.write('\n')
            f.close()
        except NameError:
            print('\nInvalid Room Type.')
    elif con == 'N':
        print('\nRecord Not Recorded.')      
    else:
        print('\nInvalid Confirmation.')
    
# sub-headings (options)        
def options():
    print('''
Choose one of the following options (0-3):
0 <-- Back to Main Menu.    
1 --> Booking Engine
2 --> Check In
3 --> Check Out''')
    
while True:
    cus = '* Customer Registration *'
    num = math.ceil(len(cus)/2)
    heading(num, cus)
    options()
    option = input('Enter your option: ')
    # Booking Engine
    if option == '1':
        boo = '*  Booking Engine *'
        num = math.ceil(len(boo)/2)
        heading(num, boo)
        customer()  
    #Check In
    elif option == '2':
        chein = '*  Check In *'
        num = math.ceil(len(chein)/2)
        heading(num, chein)
        customer()
                                       
    else:
        print("\nInvalid Option.")
        continue

【问题讨论】:

  • 您需要在某处保留更改。程序分配在程序运行时使用的内存,并在程序关闭时清除,因此您需要以某种方式持久更改。如果此程序仅用于学习目的,您可以使用文件。
  • 看模块pickle
  • @Capie 有没有使用文件使程序运行的代码示例?
  • 这能回答你的问题吗? How could I save data after closing my program?

标签: python dictionary key-value-store


【解决方案1】:

我没有执行你的代码,但是从我看到的:

这些是您的代码的第一行:

    f = open('room.txt',  'r+')
    #Hotel Rooms
    for i in range(1, 7):
        locals()['Level{}'.format(i)] = {} # Creating Dictionary
    
    start = 101
    for x in range(1, 7):
        for i in range(start, start + 10):
            eval("Level" + str(x))[i] = 'Available' # Adding Values into Dictionary
        start += 100

在这里,您创建所有房间的字典,将所有房间标记为Available。这意味着无论房间的当前值如何,都会再次标记为Available

然后在conf函数中,你重写整个文件,所以之前的ReservedUnavailable房间被再次标记为Available

这里有一个例子要清楚:

  1. 你启动程序
  2. 您预订了一个房间,(例如101号房间),它被标记为Reserved
  3. rooms.txt 文件以正确的值保存。
  4. 你停止你的程序

然后,当再次启动程序时:

  1. 创建了一个所有值都设置为Available 的字典。意思是连101房间都回Available
  2. 您预订任何其他房间(例如 201)
  3. 字典保存在您的文件中。但请记住,当您初始化您的字典时,所有房间都再次标记为Available

问题在于,在启动程序以实际加载字典中每个房间的状态时,您没有阅读 rooms.txt 文件。

我还建议您删除用于保存文件的自定义数据结构并使用 JSON 文件。它将简化您的代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多