繁体   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