我目前正在使用词典处理电话簿目录。关闭程序后,我不知道如何保存信息。我需要保存变量信息,以便稍后可以添加更多信息并打印出来。
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
答案 0 :(得分:2)
您可以将文本文件写为字符串,然后将解析读取为字典:
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())
答案 1 :(得分:1)
您可以使用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" ) )
答案 2 :(得分:0)
Pickle有效但阅读腌制物品有一些潜在的安全隐患。
另一个有用的技术是创建 phonebook.ini 文件并使用python的configparser处理它。这使您能够在文本编辑器中编辑ini文件并轻松添加条目。
**我在此解决方案中使用Python 3的新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