[英]How to print specific text from a file in python?
我正在寻找一种在文件中打印一组文本的方法。 我目前正在处理用户“查找”名称的情况,如果在文件中找到该名称,它将打印名称,地址和电话号码。
我需要知道何时找到名称,如何打印包含地址和电话号码的以下行。
这是我目前拥有的代码:
def look_up(name):
# checking if contact is already added
if name in open('contacts.txt').read():
print name
# print the address
# print the phone number
else:
# if contact not found, asks to add to book.
q = raw_input('Name not found, add to contact book?')
if q == 'yes':
# adding the info to the 'contacts.txt' file
name_new = raw_input('Enter the full name: ')
address = raw_input('Enter the address: ')
phone = raw_input('Enter the phone number: ')
f = open('contacts.txt', 'w')
f.write(name_new + '\n')
f.write(address + '\n')
f.write(phone + '\n')
f.close()
编辑
感谢这篇文章,以及@wpercy的帮助,我找到了最佳答案。
这段代码:
f = open('contacts.txt', 'r')
lines = f.readlines()
for line in lines:
if name in line:
print (line)
f.close()
允许打印包含用户传递的“名称”的给定行。
可以在下面看到@wpercy的贡献,这对组织有所帮助,使一行变成一行而不是多行! 非常感谢!
多亏了这篇文章以及@wpercy的帮助,我才能够找到最佳答案。
这段代码:
f = open('contacts.txt', 'r')
lines = f.readlines()
for line in lines:
if name in line:
print (line)
f.close()
允许打印包含用户传递的“名称”的给定行。
在评论中可以看到@wpercy的贡献,这对组织有所帮助,使一行变成一行而不是多行! 非常感谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.