Python 3.3 дамп и загрузка маринованного словаря

Я работаю над упражнениями главы в 3-й редакции Тони Гэддиса "Начинаем с Python" из класса, который я взял ранее. Я нахожусь в главе 9, и Упражнение 8 требует, чтобы я написал программу, которая выбирает словарь (имя: адрес электронной почты) для файла, когда он закрывается, и выбирает этот файл, сохраняя данные при его открытии. Я прочитал каждое слово в этой главе, и я до сих пор не понимаю, как вы можете сделать оба в одном файле. Когда вы используете функцию открытия, она создает файл, который, на мой взгляд, является новым файлом без данных. Я думаю, что это может быть проблемой секвенирования, например, в том, где размещать строки кода дампа и загрузки, но это также не имеет смысла. Логика подсказывает, что вам нужно открыть файл, прежде чем вы сможете сделать в него дамп.

Если функция 'open' создает объект файла и связывает его с файлом, и эта функция появляется в начале кода (как в def main), что удерживает ее от обнуления файла при каждом вызове этой строки?

Это не домашнее задание. Я закончил этот класс. Я делаю это для собственного наставления и буду признателен за любое объяснение, которое поможет мне понять это. Я включил мою попытку найти решение, которое отражено в приведенном ниже коде, и буду продолжать его грызть, пока не найду решение. Я просто подумал, так как генофонд здесь глубже, я бы сэкономил себе время и разочарование. Большое спасибо тем, кто решил ответить, и если мне не хватает каких-либо соответствующих данных, которые могли бы помочь прояснить этот вопрос, пожалуйста, дайте мне знать.

import pickle

#global constants for menu choices
ADDNEW = 1
LOOKUP = 2
CHANGE = 3
DELETE = 4
EXIT = 5

#create the main function
def main():

    #open the previously saved file
    friends_file = open('friends1.txt', 'rb')
    #friends = pickle.load(friends_file)
    end_of_file = False
    while not end_of_file:
        try:
            friends = pickle.load(friends_file)
            print(friends[name])
        except EOFError:
            end_of_file = True
        friends_file.close()

    #initialize variable for user's choice
    choice = 0

    while choice != EXIT:
        choice = get_menu_choice() #get user's menu choice

        #process the choice
        if choice == LOOKUP:
            lookup(friends)
        elif choice == ADDNEW:
            add(friends)
        elif choice == CHANGE:
            change(friends)
        elif choice == DELETE:
            delete(friends)

#menu choice function displays the menu and gets a validated choice from the user
def get_menu_choice():
    print()
    print('Friends and Their Email Addresses')
    print('---------------------------------')

    print('1. Add a new email')
    print('2. Look up an email')
    print('3. Change a email')
    print('4. Delete a email')
    print('5. Exit the program')
    print()

    #get the user's choice
    choice = int(input('Enter your choice: '))

    #validate the choice
    while choice < ADDNEW or choice > EXIT:
        choice = int(input('Enter a valid choice: '))
    #return the user's choice
    return choice

#the add function adds a new entry into the dictionary
def add(friends):

    #open a file to write to
    friends_file = open('friends1.txt', 'wb')

    #loop to add data to dictionary
    again = 'y'    
    while again.lower() == 'y':

        #get a name and email
        name = input('Enter a name: ')
        email = input('Enter the email address: ')

        #if the name does not exist add it
        if name not in friends:
            friends[name] = email
        else:
            print('That entry already exists')
            print()

        #add more names and emails
        again = input('Enter another person? (y/n): ')

    #save dictionary to a binary file
    pickle.dump(friends, friends1.txt)
    friends1.close()

#lookup function looks up a name in the dictionary
def lookup(friends):

    #get a name to look up
    name = input('Enter a name: ')

    #look it up in the dictionary
    print(friends.get(name, 'That name was not found.'))

#the change function changes an existing entry in the dictionary
def change(friends):
    #get a name to look up
    name = input('Enter a name: ')

    if name in friends:
        #get a new email
        email = input('Enter the new email address: ')

        #update the entry
        friends[name] = email
    else:
        print('That name is not found.')

#delete an entry from the dictionary
def delete(friends):
    #get a name to look up
    name = input('Enter a name: ')
    #if the name is found delete the entry
    if name in friends:
        del [name]
    else:
        print('That name is not found.')

#call the main function
main()

2 ответа

Используйте open("myfile", 'r+'), это позволяет выполнять как чтение, так и запись. (хотя бы в 2.7)

Если вы откроете файл для чтения с open("my_file","r") это не изменит файл. Файл должен уже существовать. Если вы откроете файл для записи с open("my_file","w") он создаст новый файл, перезаписав старый, если он существует. Первая форма (чтение) используется по умолчанию, поэтому вы можете опустить вторую "r" аргумент, если хотите. Это описано в документации по стандартной библиотеке Python.

Другие вопросы по тегам