使用我的last question,我的程序无法检测到短语并将其与第一行以外的任何行匹配。但是,我解决了并解决了问题。但现在我需要一个新的def
函数,删除某个(给定的refName
)联系人以及它下面与该联系人关联的4行,但是,我有和readfile
函数一样的问题;它会检测第一行,而不是其他任何内容。
READFILE
def readFile(self):
lookup = input("Type in a contact REFERENCE name.\n")
with open('contacts.txt') as myFile:
my_file_iter = iter(myFile)
for num, line in enumerate(my_file_iter, 1):
if lookup.upper() in line:
print(line)
print(next(my_file_iter))
print(next(my_file_iter))
print(next(my_file_iter))
print(next(my_file_iter))
break
else:
print("Contact not found.")
self.managerMenu()
delContact
def delContact(self):
lookup = input("Type in a contact REFERENCE name.\n")
with open('contacts.txt') as myFile:
my_file_iter = iter(myFile)
for num, line in enumerate(my_file_iter, 1):
if lookup.upper() != "YOU":
if lookup.upper() in line:
# read a list of lines into data
data = myFile.readlines()
print("Deleting contact ", data[num - 1][9:])
# now change the lines, note that you have to add a newline
data[num - 1] = ''
data[num] = ''
data[num + 1] = ''
data[num + 2] = ''
data[num + 3] = ''
# and write everything back
myFile.writelines( data )
break
else:
print("Contact not found.")
break
else:
print("Cannot delete yourself!")
self.delContact()
self.managerMenu()
CONTACTS.TXT
Contact: YOU
First Name: FELIX
Last Name: MARTIN
Number: (555)-555-5554
Address: 3550 VISTA PARK DRIVE
Contact: FRIEND
First Name: DAVID
Last Name: BRENNEMAN
Number: (555)-555-5555
Address: 123 SESAME STREET
Contact: MOM
First Name: SANDY
Last Name: MARTIN
Number: (555)-555-5556
Address: 3550 VISTA PARK DRIVE
当我运行程序时,readfile和delcontact都会发生这种情况。
(请记住,代码摘录和程序的某些部分是整个项目的一部分,这里没有提到,以清除任何混淆。整个文件将在最后标记。)
readFile
Contact Manager v1.4 - Felix Martin
Loading... Loaded!
Welcome, FELIX
Available Commands: Info, ReadFile, DeleteContact, EditContact, AddContact, quit()
readfile
Type in a contact REFERENCE name.
you
Contact: YOU
First Name: FELIX
Last Name: MARTIN
Number: (555)-555-5554
Address: 3550 VISTA PARK DRIVE
Available Commands: Info, ReadFile, DeleteContact, EditContact, AddContact, quit()
readfile
Type in a contact REFERENCE name.
friend
Contact: FRIEND
First Name: DAVID
Last Name: BRENNEMAN
Number: (555)-555-5555
Address: 123 SESAME STREET
Available Commands: Info, ReadFile, DeleteContact, EditContact, AddContact, quit()
delContact
Contact Manager v1.4 - Felix Martin
Loading... Loaded!
Welcome, FELIX
Available Commands: Info, ReadFile, DeleteContact, EditContact, AddContact, quit()
deletecontact
Type in a contact REFERENCE name.
you
Cannot delete yourself!
Type in a contact REFERENCE name.
friend
Contact not found.
Available Commands: Info, ReadFile, DeleteContact, EditContact, AddContact, quit()
有什么想法吗?我要求在提交答案时,我更喜欢按照我展示的方式完成,而不是使用RegEx,如果可能的话,在Python 3.4中。
答案 0 :(得分:1)
你有同样的问题,基本上就是你在第一个问题上遇到的问题。 行
else:
print("Contact not found.")
break
应该是“循环其他”。也就是说,它们应缩进到与for
相同的级别。实际上,你正在查看文件的第一行,如果联系人不在那里,你就放弃了。
我不知道代码中可能存在的其他问题(如果有的话)。
答案 1 :(得分:1)
听起来您需要一个更全面的工具集来处理您的数据。如果您正在学习(非常有价值的)新模块,我强烈建议将此数据迁移到某种类型的数据库中。 sqlite3
是Python的 database du jour ,从Python 2.5开始包含在标准库中。
那就是说,如果你致力于把它变成一个平面文件,听起来你真的需要一个函数来建立一个像字典更有用的数据的工作副本。我建议在应用程序运行时立即运行它,并引用数据库以进行任何进一步的调用。
def build_db(path):
db = {}
with open(path) as f:
for line in f:
category, value = map(str.strip, line.split(":"))
if category == "CONTACT":
cur_contact = value
db[value] = {}
else:
db.get(cur_contact, {})[category] = value
# builds a dictionary of dictionaries that looks like:
# # {"YOU": {"First Name": "FELIX", "Last Name": "MARTIN", ...}, ...}
return db
然后在您的应用程序的入口点,您可以写:
db = build_db("path/to/your/file.txt")
从那里开始,通过您设计的API访问db
对象来处理任何读取或写入。
def read_contact(db, contact_name):
formatting = """\
CONTACT: {contact}
First Name: {First Name}
Last Name: {Last Name}
Number: {Number}
Address: {Address}
"""
contact_info = db.get(contact_name)
if contact_info is None:
raise KeyError("No such contact: {}".format(contact_name))
contact_info['contact'] = contact_name
return formatting.format(**contact_info)
def write_db_to_file(db, out_path):
with open(out_path, 'w') as outf:
for contact_name in db:
outf.write(read_contact(db, contact_name))
def remove_user_from_db(db, contact_name):
try:
del db[contact_name]
except KeyError:
raise KeyError("No such contact: {}".format(contact_name))