簡體   English   中英

如何查找和檢查文件中的特定單詞然后將其刪除

[英]How to find and check for a specific word in a file and then delete it

我的文本包含 1234:zakasi:2:1:3 形式的學生數據(學生 id ,name , sem ,yrs , course)

我想首先檢查學生 id 是否在文件中,然后刪除 id 所在的整行,如果是的話

infile = open("students.dat","r")
f = infile.readlines()
id = input('enter your id:')
new_list = []
for line in f:
    for item in line.split(':'):
    new_list.append(item)
    if id in new_list[0]:
        # delete the line its found in
with open("students.dat","r") as infile:
f = infile.readlines()
student_id = input('enter your id:')
new_list = []
lines_kept = []
for line in f:
    for item in line.split(':'):
    new_list.append(item)
    if student_id in new_list[0]:
        # delete the line its found in
        print("Found instance")
    else:
        lines_kept.append(line)


# Writing part
with open("students.dat","w") as outfile:
    outfile.write("\n".join(lines_kept))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM