【问题标题】:Iterate over a file遍历文件
【发布时间】:2021-05-17 18:01:54
【问题描述】:

我想用 Python 打开一个文件。 对于文件中的每一行,用line.split(" ") 分割它,
这样它就会访问第一个单词。

然后检查单词是否等于给定字符串“TEST”。如果是这种情况,请删除该行,否则保留它。

我尝试使用readlines() 来读取这些行。那行得通,但后来我不知道如何删除整行。

这是我目前的代码

def delete_client(client):
    f = open("clients.md", "r")
    data = f.readlines()

    f = open("clients.md", "w")
    for line_counter in range(len(data)):
        splitted_line = data[line_counter].strip("\n").split()[0]
        print("\n" + splitted_line)

        if client == splitted_line:
            print("Equal to client")
            f.write("HELLO")
        else:
            print("Not equal to client")

    f.close

delete_client("DELETE_ME")

客户文件

first 192.168.0.14 Lukas administrator
another text 192.168.0.14 Lukas administrator
DELETE_ME 192.168.0.14 Lukas administrator
fourth 192.168.0.14 Lukas administrator

【问题讨论】:

    标签: python file text split iterator


    【解决方案1】:

    else: 块应该将该行写入文件。并删除将HELLO 写入文件的行(除非您真的希望它替换已删除的行)。

            if client == splitted_line:
                print("Equal to client")
            else:
                print("Not equal to client")
                f.write(data[line_counter])
    

    【讨论】:

      【解决方案2】:

      使用列表推导创建另一个列表,其中不包含您要删除的行并将这些行写回原始文件。

      def delete_client(client):
        with open('clients.md', 'r') as f:
          data = f.readlines()
      
        lines_to_keep  = [line for line in data if line.split(' ')[0] != client]
        
        with open('clients.md', 'w')as f:
          f.writelines(lines_to_keep)
          
      delete_client("DELETE_ME")
      

      【讨论】:

        【解决方案3】:

        您无法使用以下方法模拟您想要的行为:

        import fileinput
        
        for line in fileinput.input(files=('clients.md'), inplace=True, backup='.old'):
            if not line.startswith('DELETE_ME'):
                print(line, end='')
        

        或者,“普通的旧”方式也可以;

        with open('clients.md', 'r') as in_file:
            content = in_file.readlines()
            
        with open('clients.md', 'w') as out_file:
            out_file.writelines(filter(lambda x: not x.startswith('DELETE_ME'), content))
        

        此外,在读取/写入文件时,您应该使用with-blocks 来确保文件指针正确打开/关闭。

        【讨论】:

          【解决方案4】:

          你可以使用:

          def dc(word):
            with open("text.txt") as f:
              i =  [l for l in f if not l.startswith(word)]
            with open("text.txt", "w") as w:
              print(*i)
              for l in i:
                w.write(l)
            
          word = "DELETE_ME"
          dc(word)
          

          Demo

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2023-03-03
            • 2018-10-06
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2023-01-09
            • 2016-02-04
            • 2012-05-07
            相关资源
            最近更新 更多