Home > database >  delete only 1 instance of a string from a file
delete only 1 instance of a string from a file

Time:11-13

I want to be able to ask the user for an input(the student number at the beginning of each line) and then ask which course they want to delete(the course codes are the list). So the program would delete the course from the list in the student number without deleting other instances of the course. Cause other students have the same courses.

CodePudding user response:

Welcome to the site. You have a little ways to go to make this work. It would be good if you put some additional effort in to this before asking somebody to code this up. Let me suggest a structure for you that perhaps you can work on/augment and then you can re-post if you get stuck by editing your question above and/or commenting back on this answer. Here is a framework that I suggest:

  1. make a section of code to read in your whole .dat file into memory. I would suggest putting the data into a dictionary that looks like this:

data = {1001: (name, email, <whatever the digits stand for>, [SRT111, OPS333, ...],
1044: ( ... )}

basically a dictionary with the ID as the key and the rest in a tuple or list. Test that, make sure it works OK by inspecting a few values.

  1. Make a little "control loop" that uses your input statements, and see if you can locate the "record" from your dictionary. Add some "if" logic to do "something" if the ID is not found or if the user enters something like "quit" to exit/break the loop. Test it to make sure it can find the ID's and then test it again to see that it can find the course in the list inside the tuple/list with the data. You probably need another "if" statement in there to "do something" if the course is not in the data element. Test it.

  2. Make a little "helper function" that can re-write a data element with the course removed. A suggested signature would be:


def remove_course(data_element, course):
    # make the new data element (name, ... , [reduced course list]
    return new_data_element

Test it, make sure it works.

  1. Put those pieces together and you should have the ingredients to change the dictionary by using the loop and function to put the new data element into the dictionary, over-writing the old one.

  2. Write a widget to write the new .dat file from the dictionary in its entirety.

EDIT:

You can make the dictionary from a data file with something like this:

filename = 'student_data.dat'
data = {}  # an empty dictionary to stuff the results in

# use a context manager to handle opening/closing the file...
with open(filename, 'r') as src:
    # loop through the lines
    for line in src:
        # strip any whitespace from the end and tokenize the line by ":"
        tokens = line.strip().split(':')
        # check it...  (remove later)
        print(tokens)
        # gather the pieces, make conversions as necessary...
        stu_id = int(tokens[0])
        name = tokens[1]
        email = tokens[2]
        some_number = int(tokens[3])
        # splitting the number from the list of courses is a little complicated
        # you *could* do this more elegantly with regex, but for your level, 
        # here is a simple way to find the "chop points" and split this up...
        last_blobs = tokens[4].split('[')
        course_count = int(last_blobs[0])
        course_list = last_blobs[1][:-1]  # everything except the last bracket
        # split up the courses by comma
        courses = course_list.split(',')

        # now stuff that into the dictionary...
        # a little sanity check:
        if data.get(stu_id):
            print(f'duplicate ID found: {stu_id}.  OVERWRITING')
        data[stu_id] = (name,
                        email,
                        some_number,
                        course_count,
                        courses)

for key, value in data.items():
    print(key, value)

CodePudding user response:

i got something for you. What you want to do is to find the student first and then delete the course: like this.

studentid = input("enter studentid")
course = input("enter the course to delete")
with open("studentDatabase.dat") as file:
    f = file.readlines()
with open("studentDatabase.dat","w") as file:
    for line in lines:
        if studentid in line:               # Check if it's the right sudent 
            line = line.replace(course, "") # replace course with nothing
            file.write(line)

You want to check if we are looking at the correct student, then replace the line but without the course code. Hope you can find it useful.

  • Related