python - 遍历一个文件

标签 python file text split iterator

我想用 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

最佳答案

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

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

关于python - 遍历一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66198060/

相关文章:

python - 从 Python 中的句子集中删除最常见单词的停用词

python - Pandas - 按一列分组,按另一列排序,从第三列获取值

Python 导入机制

html - Chrome 35 DirectWrite(默认打开)破坏了我的网站菜单

iphone - 标签的自定义 UIColor

使用自定义列作为索引的 Python Pandas 到 CSV

JavaScript NodeJs 开放库

swift - 在上一个 swift 版本中下载文件

c++ 为什么 .ignore() 函数不能正常工作?

android - 动态设置指向 strings.xml 中文本的链接