如果它包含某个字符串值,如何读取文本文件并删除它和关联的行?

时间:2018-06-01 04:07:28

标签: python python-3.x

例如,如果我有一个带有基本电话簿信息的.txt文件,我想从上述txt文件中删除包含“city = Seattle”之类的行。但是,有些名称可能会在输入后包含一些额外的行或注释,我也想要这样做。如下:

  

姓名= John Doe,地址= 25 Main St,City = Denver,Phone = 1-310-999-9999

     

注意:约翰有一只狗

     

姓名= Jane Doe,地址= 12 Richard Rd,City = Seattle,Phone =   1-310-999-9999

     

注意:Jane对坚果过敏

     

姓名=迈克尔史密斯,地址= 25加州BLVD,城市=洛杉矶,电话=   1-310-999-9999

在script.py运行之后(并从西雅图删除列表)

  

姓名= John Doe,地址= 25 California BLVD,City = Denver,Phone =   1-310-999-9999

     

注意:约翰有一只狗

     

姓名=迈克尔史密斯,地址= 25加州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)

1 个答案:

答案 0 :(得分:0)

如果当前行不包含" 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()