我有一个函数将联系人写入数据库,然后用其他函数进行管理(整个程序将在帖子的末尾列为GitHub链接),然后使用{写回文件{1}}功能。但是,我有write_db_to_file
字典用我的db
函数构建,如果有任何额外的行或空格,或者任何不属于的东西,那么程序会在启动时中断,因为它是没有找到它在文件中寻找的内容(build_db
)
以下是ValueError: need more than 1 value to unpack
功能:
build_db
以下是def build_db(path, mode=0):
if mode == 0:
db = {}
if os.path.exists('contacts.txt') == False:
with open('contacts.txt', 'w') as f:
f.write('CONTACT: DEV')
f.write('\n First Name: FELIX')
f.write('\n Last Name: MARTIN')
f.write('\n Number: N/A')
f.write('\n Address: N/A')
print("Please re-run the program.")
quit()
else:
#while opening contacts.txt as f
with open(path) as f:
for line in f:
#strip the file and split each line from the 'CATEGORY' and the 'VALUE'
#e.g. split 'CONTACT: YOU' to 'CONTACT', 'YOU'
category, value = map(str.strip, line.split(":"))
#if the stripped line is the CONTACT line
if category == "CONTACT":
#set the current contact to start a new dictionary with the value of the contact
cur_contact = value
db[value] = {}
#if the stripped line is the data within the CONTACT line
else:
#set the previously set dictionarys data with another dictionary
db.get(cur_contact, {})[category] = value
#return the database when its called
return db
#unless debug mode is set to 1
else:
#do everything as before, except print data for debugging
db = {}
with open(path) as f:
for line in f:
category, value = map(str.strip, line.split(":"))
mapDebug = map(str.strip, line.split(":"))
print("Printing mapDebug\n")
print(mapDebug)
print("Printing category, value\n")
print(category, value)
if category == "CONTACT":
cur_contact = value
db[value] = {}
print("Printing db[value]\n")
print(db[value])
else:
print("Printing db.get(cur_contact, {})[category]\n")
print(db.get(cur_contact, {})[category])
db.get(cur_contact, {})[category] = value
print(db)
return db
#finally, build the database off of the local contacts.txt file
db = build_db("contacts.txt")
功能:
write_db_to_file
假设 def write_db_to_file(self, db, out_path):
with open(out_path, 'w+') as outf:
#for each contact
for contact_name in db:
#write the values of each in the correct format
outf.write(self.read_contact(db, contact_name.upper()))
#DEBUG/NOT WORKING: clear any blank lines
for line in outf:
if not line.isspace():
outf.write(line)
self.contact_manager(db)
如下:
contacts.txt
在我的计划中键入CONTACT: DEV
First Name: FELIX
Last Name: MARTIN
Number: N/A
Address: N/A
CONTACT: FRIEND
First Name: JIHAD
Last Name: FAIR
Number: N/A
Address: 49 AMBER LN
,然后FRIEND将从delcontact
删除FRIEND联系人。
db
最后,我输入Type a command, help or quit to exit the program.
debug()
Activating DEBUG Function.
{'DEV': {'Last Name': 'MARTIN', 'First Name': 'FELIX', 'Number': 'N/A', 'Address': 'N/A'}, 'FRIEND': {'Last Name': 'FAIR', 'First Name': 'JIHAD', 'Number': 'N/A', 'Address': '49 AMBER LN'}}
Type a command, help or quit to exit the program.
delcontact
What contact shall you delete?
friend
Type a command, help or quit to exit the program.
debug()
Activating DEBUG Function.
{'DEV': {'Last Name': 'MARTIN', 'First Name': 'FELIX', 'Number': 'N/A', 'Address': 'N/A'}}
Type a command, help or quit to exit the program.
。它成功覆盖了最新writefile
的文件。但是,它在文件末尾留下一个空白区域。因此,下次他们启动程序时,会出现我之前谈到的错误:
db
因为上次运行的Contact Manager - Felix Martin V2.8.1
LOADING . . .
LOADED!
Type a command, help or quit to exit the program.
debug()
Activating DEBUG Function.
{'DEV': {'First Name': 'FELIX', 'Address': 'N/A', 'Number': 'N/A', 'Last Name': 'MARTIN'}}
Type a command, help or quit to exit the program.
addcontact
What is the contacts reference name?
friend
What is the contacts first name?
jihad
What is the contacts last name?
fair
What is the contacts (cell/main/home/etc) number?
n/a
What is the contacts address?
49 amber ln
Traceback (most recent call last):
File "/home/ubuntu/workspace/personal/contactManager.py", line 235, in <module>
App()
File "/home/ubuntu/workspace/personal/contactManager.py", line 71, in __init__
self.contact_manager(db)
File "/home/ubuntu/workspace/personal/contactManager.py", line 228, in contact_manager
self.contact_manager(db)
File "/home/ubuntu/workspace/personal/contactManager.py", line 202, in contact_manager
self.add_contact_to_db(db, input("What is the contacts reference name?\n").upper(), input("What is the contacts first name?\n").upper(), input("What is the contacts last name?\n").upper(), input("What is the contacts (cell/main/home/etc) number?\n").upper(), input("What is the contacts address?\n").upper())
File "/home/ubuntu/workspace/personal/contactManager.py", line 114, in add_contact_to_db
db = build_db("contacts.txt")
File "/home/ubuntu/workspace/personal/contactManager.py", line 24, in build_db
category, value = map(str.strip, line.split(":"))
ValueError: need more than 1 value to unpack
函数留下了空格。
如何摆脱文件中的空白行?
答案 0 :(得分:1)
好吧,如果有人克隆了repo来查看它,那么将一些代码添加到一个选项中以修复问题是个好主意,他们可以完全按照你在问题中描述的那样重现问题!将问题标记为python3或者说你在某处使用python3也是一个好主意,这样如果有人试图运行它,它就会运行。
无论如何这里是我得到的。
源代码中的read_contact
函数(ln 144)定义formatting
函数的write_bd_to_file
字符串,如下所示&#34;
def read_contact(self, db,contact_name):
formatting = """\
CONTACT: {contact},
First Name: {First Name},
... and so on
Address: {}
"""
这将在address: {contact}
之后插入一个换行符,在添加新联系人之后写入db时,应用程序会从文件重新初始化自己。当它返回读取文件时,由于此代码,DEV之后有一个空行。此字符串与写入相同:
formatting="CONTACT:{contact},\n\tFirst Name:{first name},\n ...Address:{Address}\n"
你逃过了领先的换行符,但没有追踪尾随换行符。您可以通过从结尾删除换行来解决此问题:
"""\
CONTACT: {contact},
First Name: {First Name},
... and so on
Address: {}\
"""
或只是:
"""CONTACT: {contact},
First Name: {First Name},
... and so on
Address: {}"""
回应你的评论:
我明白你在说什么。我认为这需要您解决一个轻微的设计问题。在某些情况下,使用read_contact
中的格式字符串将联系人写入文件但是在其他地方使用这样的代码将其写入文件。
outf.write('\n CONTACT:' +contact_info['contact'])
outf.write('\n First Name: ' +contact_info['First Name'])
...
你应该真正将所有文件都写入由一个函数处理的文件中。我建议编辑函数read_contact
以获取contact_info
而不是db
这样的字典。解析db
和contact_name
参数的函数部分可以分成另一个函数,然后将其contact_info
dict交给返回格式化字符串的函数。
def format_contact_info(self contact_info):
formatting = """CONTACT:{contact}
"First Name: {First Name}
"Last Name: {Last Name}
"Number: {Number}
"Address: {Address}"""
return formatting.format(**contact_info)
然后是add_contact_to_db
函数
with open('contacts.txt', 'a+') as f:
#write the data **Replace this block with**
#f.write("\nCONTACT: " + contact_info['contact'])
#f.write("\n First Name: " + contact_info['First Name'])
#f.write("\n Last Name: " + contact_info['Last Name'])
#f.write("\n Number: " + contact_info['Number'])
#f.write("\n Address: " + contact_info['Address'])
#rebuild the db
f.write("\n"+self.format_contact_info(contact_info))
db = build_db("contacts.txt")
并在write_db_to_file
for contact_name in db:
this_contact = self.extract(contact_name.upper(), db)
outf.write(self.format_contact_info(this_contact))
outf.write('\n')
并且extract
函数正在执行旧read_contact
函数
def extract(self, contact_name, db):
contact_name = contact_name.upper()
contact_info = db.get(contact_name)
contact_info['contact'] = contact_name
return contact_info