[英]How to read a text file and delete it and associated lines, if it contains a certain string value?
例如,如果我有一个包含基本电话簿信息的.txt文件,并且想要从所述txt文件中删除包含“ city = Seattle”之类的行。 但是,某些名称在条目后可能包含一些额外的行或注释,我也想删除这些名称。 如以下内容:
名称= John Doe,地址= 25 Main St,城市= Denver,电话= 1-310-999-9999
注意:约翰有一只狗
名称=简·多伊(Jane Doe),地址= 12理查德路(Richard Rd),城市=西雅图,电话= 1-310-999-9999
注意:简对坚果过敏
名称= Michael Smith,地址= 25 California BLVD,城市=洛杉矶,电话= 1-310-999-9999
运行script.py之后(并从西雅图删除列表)
名称= John Doe,地址= 25 California BLVD,城市= Denver,电话= 1-310-999-9999
注意:约翰有一只狗
名称= Michael Smith,地址= 25 California BLVD,城市=洛杉矶,电话= 1-310-999-9999 *
这就是我所拥有的,但是我不知道如何处理一些可能要删除便笺或日志条目的名称
#read in my text file
file = open("phonebook.txt","r")
allLines = file.readlines()
file.close()
#rewrite my text file now
file = open("phonebook.txt","w")
#rewrite allLines into my text file but skip lines that contain seattle
for line in allLines:
if "seattle" not in line:
file.write(line)
遍历备用行,如果当前行不包含“ city = seattle”,则写入当前行和下一行。
#read in my text file
file = open("phonebook.txt","r")
allLines = file.readlines()
file.close()
allLines = list(filter(None, allLines))
#rewrite my text file now
file = open("phonebook.txt","w")
#rewrite allLines into my text file but skip lines that contain seattle
for x in range(0, len(allLines), 2):
if "city=seattle" not in allLines[x].casefold():
file.write(allLines[x])
try:
file.write(allLines[x+1])
except IndexError:
print('end')
file.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.