Python 关闭程序后如何保存数据?

Python 关闭程序后如何保存数据?,python,dictionary,save,raw-input,Python,Dictionary,Save,Raw Input,我目前正在使用字典编写电话簿目录。关闭程序后,我不知道如何保存信息。我需要保存变量信息,以便以后可以添加更多并打印它 Information={"Police":911} def NewEntry(): Name=raw_input("What is the targets name?") Number=raw_input("What is the target's number?") Number=int(Number)

我目前正在使用字典编写电话簿目录。关闭程序后,我不知道如何保存信息。我需要保存变量信息,以便以后可以添加更多并打印它

    Information={"Police":911}
    def NewEntry():
        Name=raw_input("What is the targets name?")
        Number=raw_input("What is the target's number?")
        Number=int(Number)
        Information[Name]=Number

    NewEntry()
    print Information
编辑:我现在使用Pickle模块,这是我当前的代码,但它不工作:

     import pickle
     Information={"Police":911}
     pickle.dump(Information,open("save.p","wb"))
      def NewEntry():
         Name=raw_input("What is the targets name?")
         Number=raw_input("What is the target's number?")
         Number=int(Number)
         Information[Name]=Number
    Information=pickle.load(open("save.p","rb"))
    NewEntry()
    pickle.dump(Information,open("save.p","wb"))
    print Information
您可以使用以下模块:

或:

您可以使用以下模块:

或:


您可以将文本文件作为字符串写入,然后将解析作为字典读取:

Write

with open('info.txt', 'w') as f:
    f.write(str(your_dict))
读取

import ast

with open('info.txt', 'r') as f:
    your_dict = ast.literal_eval(f.read())

您可以将文本文件作为字符串写入,然后将解析作为字典读取:

Write

with open('info.txt', 'w') as f:
    f.write(str(your_dict))
读取

import ast

with open('info.txt', 'r') as f:
    your_dict = ast.literal_eval(f.read())

Pickle可以工作,但在Pickle对象中读取存在一些潜在的安全风险

另一种有用的技术是创建一个phonebook.ini文件,并使用python的configparser进行处理。这使您能够在文本编辑器中编辑ini文件并轻松添加条目

**我在这个解决方案中使用了Python3新的f字符串,并将“Information”重命名为“phonebook”,以遵守标准变量命名约定

您可能希望为强健的解决方案添加一些错误处理,但这不利于您:

import configparser

INI_FN = 'phonebook.ini'


def ini_file_create(phonebook):
    ''' Create and populate the program's .ini file'''
    with open(INI_FN, 'w') as f:
        # write useful readable info at the top of the ini file
        f.write(f'# This INI file saves phonebook entries\n')
        f.write(f'# New numbers can be added under [PHONEBOOK]\n#\n')
        f.write(f'# ONLY EDIT WITH "Notepad" SINCE THIS IS A RAW TEXT FILE!\n\n\n')
        f.write(f"# Maps the name to a phone number\n")
        f.write(f'[PHONEBOOK]\n')
        # save all the phonebook entries
        for entry, number in phonebook.items():
            f.write(f'{entry} = {number}\n')
        f.close()


def ini_file_read():
    ''' Read the saved phonebook from INI_FN .ini file'''
    # process the ini file and setup all mappings for parsing the bank CSV file
    config = configparser.ConfigParser()
    config.read(INI_FN)
    phonebook = dict()
    for entry in config['PHONEBOOK']:
        phonebook[entry] = config['PHONEBOOK'][entry]
    return phonebook

# populate the phonebook with some example numbers
phonebook = {"Police": 911}
phonebook['Doc'] = 554

# example call to save the phonebook
ini_file_create(phonebook)

# example call to read the previously saved phonebook
phonebook = ini_file_read()
以下是创建的phonebook.ini文件的内容

# This INI file saves phonebook entries
# New numbers can be added under [PHONEBOOK]
#
# ONLY EDIT WITH "Notepad" SINCE THIS IS A RAW TEXT FILE!


# Maps the name to a phone number
[PHONEBOOK]
Police = 911
Doc = 554

Pickle可以工作,但在Pickle对象中读取存在一些潜在的安全风险

另一种有用的技术是创建一个phonebook.ini文件,并使用python的configparser进行处理。这使您能够在文本编辑器中编辑ini文件并轻松添加条目

**我在这个解决方案中使用了Python3新的f字符串,并将“Information”重命名为“phonebook”,以遵守标准变量命名约定

您可能希望为强健的解决方案添加一些错误处理,但这不利于您:

import configparser

INI_FN = 'phonebook.ini'


def ini_file_create(phonebook):
    ''' Create and populate the program's .ini file'''
    with open(INI_FN, 'w') as f:
        # write useful readable info at the top of the ini file
        f.write(f'# This INI file saves phonebook entries\n')
        f.write(f'# New numbers can be added under [PHONEBOOK]\n#\n')
        f.write(f'# ONLY EDIT WITH "Notepad" SINCE THIS IS A RAW TEXT FILE!\n\n\n')
        f.write(f"# Maps the name to a phone number\n")
        f.write(f'[PHONEBOOK]\n')
        # save all the phonebook entries
        for entry, number in phonebook.items():
            f.write(f'{entry} = {number}\n')
        f.close()


def ini_file_read():
    ''' Read the saved phonebook from INI_FN .ini file'''
    # process the ini file and setup all mappings for parsing the bank CSV file
    config = configparser.ConfigParser()
    config.read(INI_FN)
    phonebook = dict()
    for entry in config['PHONEBOOK']:
        phonebook[entry] = config['PHONEBOOK'][entry]
    return phonebook

# populate the phonebook with some example numbers
phonebook = {"Police": 911}
phonebook['Doc'] = 554

# example call to save the phonebook
ini_file_create(phonebook)

# example call to read the previously saved phonebook
phonebook = ini_file_read()
以下是创建的phonebook.ini文件的内容

# This INI file saves phonebook entries
# New numbers can be added under [PHONEBOOK]
#
# ONLY EDIT WITH "Notepad" SINCE THIS IS A RAW TEXT FILE!


# Maps the name to a phone number
[PHONEBOOK]
Police = 911
Doc = 554