【问题标题】:system is not writing into original dictionary file系统未写入原始字典文件
【发布时间】:2021-07-17 00:48:37
【问题描述】:
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

如您所见,系统并未将数据写入原始字典。我们该如何改进呢?请详细解释。谢谢大家

【问题讨论】:

  • 您为什么使用文本内容的图像?您可以将文本直接复制并粘贴到您的问题中。只有在没有其他方法可以证明问题时才应使用图片。

标签: python-3.x file dictionary


【解决方案1】:

Python 不只是建立这样的关系。从 Python 的角度来看,您正在读取一个常规文本文件,并从 read 行执行一个命令。该命令创建一个与创建它的行无关的对象。但是在我看来,写入文件应该仍然有效。但是您又移动了一行(因为您读取了数据所在的行,而现在您在它的末尾)。

当您读取文件时,我们在文件上的位置会发生变化。像这样迭代文件(即for line in file:)在文件上隐式调用next()。出于效率原因,定位被禁用(file.tell() 不会告诉当前位置)。当您写入文件时,由于某种原因,您将文本附加到末尾,如果您对其进行测试,它将不再继续循环,即使它仍在第二行。

同时读写看起来像undefined behaviour

Beginner Python: Reading and writing to the same file

【讨论】:

  • 正确@Nononono
猜你喜欢
  • 2012-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多