关闭程序后如何保存数据?
Posted
技术标签:
【中文标题】关闭程序后如何保存数据?【英文标题】:How could I save data after closing my program? 【发布时间】:2015-02-22 18:53:24 【问题描述】:我目前正在使用字典制作电话簿目录。关闭程序后,我不知道有什么方法可以保存信息。我需要保存变量信息,以便以后添加更多并打印。
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
【问题讨论】:
【参考方案1】:您可以将文本文件作为字符串写入,然后读取解析为字典:
Write
with open('info.txt', 'w') as f:
f.write(str(your_dict))
Read
import ast
with open('info.txt', 'r') as f:
your_dict = ast.literal_eval(f.read())
【讨论】:
【参考方案2】:您可以使用Pickle 模块:
import pickle
# Save a dictionary into a pickle file.
favorite_color = "lion": "yellow", "kitty": "red"
pickle.dump( favorite_color, open( "save.p", "wb" ) )
或者:
# Load the dictionary back from the pickle file.
favorite_color = pickle.load( open( "save.p", "rb" ) )
【讨论】:
【参考方案3】:Pickle 有效,但读取腌制对象存在一些潜在的安全风险。
另一个有用的技术是创建一个 phonebook.ini 文件并使用 python 的 configparser 处理它。这使您能够在文本编辑器中编辑 ini 文件并轻松添加条目。
** 我在此解决方案中使用 Python 3 的新 f 字符串,并将“信息”重命名为“电话簿”以遵守标准变量命名约定
您可能希望为强大的解决方案添加一些错误处理,但这说明了您的观点:
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
【讨论】:
以上是关于关闭程序后如何保存数据?的主要内容,如果未能解决你的问题,请参考以下文章