[英]Iterate over a file
我想在 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:
塊應該將該行寫入文件。 並刪除將HELLO
寫入文件的行(除非您真的希望它替換已刪除的行)。
if client == splitted_line:
print("Equal to client")
else:
print("Not equal to client")
f.write(data[line_counter])
使用列表推導創建另一個列表,其中不包含您要刪除的行並將這些行寫回原始文件。
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")
您無法使用以下方法模擬您想要的行為:
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 以確保正確打開/關閉文件指針。
您可以使用:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.