0
def update(login_info):
    stids = 001
    file = open('regis.txt', 'r+')
    for line in file:
        if stids in line:
            x = eval(line)
            print(x)
            c = input('what course you would like to update >> ')
            get = x.get(c)
            print('This is your current mark for the course', get)
            mark = input('What is the new mark? >>')
            g = mark.upper()
            x.update({c: g})
            file.write(str(x))

Before writing into the file

After writing into the file

This is what happens in the idle

As you can see, the system is not writing the data into the original dictionary. How can we improve on that? Pls, explain in detail. Thx all

mushrooms
  • 1
  • 2
  • Why are you using images of text content? You can copy and paste the text directly into your question. Images should only be used when there is no other way to demonstrate the issue. – Ken White Jul 17 '21 at 00:52

1 Answers1

0

Python doesn't just make relations like that. In Python's perspective, you are reading a regular text file, executing a command from the line read. That command creates an object which has no relationship to the line it was created from. But writing to the file should still work in my opinion. But you moved a line further (because you read the line where the data was and now you are at the end of it).

When you read a file, the position of where we are on the file changes. Iterating over the file like that (i.e for line in file:) invokes implicitly next() on the file. For efficiency reasons, positioning is disabled (file.tell() will not tell the current position). When you wrote to the file, for some reason you appended the text to the end, and if you test it it will no longer continue the loop even though it is still on the second line.

Reading and writing at the same time looks like an undefined behaviour.

Beginner Python: Reading and writing to the same file

NONONONONO
  • 612
  • 1
  • 6
  • 10