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