为什么JSON解码错误对应这个特定函数被运行的次数?

2024-10-03 13:21:52 发布

您现在位置:Python中文网/ 问答频道 /正文

提前:我为含糊不清的问题和冗长的描述道歉。我一辈子都不能找出问题所在,现在我已经绝望了

这是一个在命令行上运行的小程序。它允许用户添加或更新条目。这些条目是字典的键值对——字典最初是一个文本文件,与名为info.txt的脚本处于同一级别,它必须用“{}”(我知道,糟糕的程序)实例化。我稍后会解决问题)。总之,它读取一个文本文件,将其转换为一个JSON对象进行操作,然后写回文本文件

剧本:

import os
import json
import sys


def addNew():

    with open(os.path.join(os.path.abspath(os.path.dirname(__file__)),
              "info.txt")) as entryFile:
        entryDict = json.load(entryFile)

    newEntry = sys.argv[1]
    newValue = sys.argv[2]
    confirmNew = input("Add \"{0}\" with \"{1}\" to the dictionary?"
                       "\ny or n\n".format(newEntry, newValue))

    if confirmNew == "y":
        entryDict[newEntry] = newValue
        print("You have added {} to your dictionary".format(newEntry))
    else:
        print("You have not added a new entry")

    entryString = json.dumps(entryDict)

    with open(os.path.join(os.path.abspath(os.path.dirname(__file__)),
              "info.txt"), "r+") as entryFile:
        entryFile.write(entryString)


def update():
    print("An entry with this name already exists.")

    entryFile = open(os.path.join(os.path.abspath(os.path.dirname(__file__)),                     
        "info.txt"), "r+")

    entryDict = json.load(entryFile)
    confirmUpdate = input("Update '{0}' with '{1}'?\n"
                          .format(sys.argv[1], sys.argv[2]))
    if confirmUpdate == "y":
        entryDict.update({str(sys.argv[1]): sys.argv[2]})

    entryString = json.dumps(entryDict)
    entryFile.truncate(0)
    entryFile.write(entryString)
    entryFile.close()
    print("{} has been updated.".format(sys.argv[1]))


def main():

    entryFile = open(os.path.join(os.path.abspath(os.path.dirname(__file__)),         
    "info.txt"))
    entryDict = json.load(entryFile)
    entryFile.close()

    if len(sys.argv) < 2:
        print('usage: python3 {} entry value - entry manager '
              '\nentry: name of entry and its value to add to the dict.'
              .format(sys.argv[0]))
        sys.exit()

    if len(sys.argv) == 3 and not sys.argv[1] in entryDict:
        addNew()
        sys.exit()

    if len(sys.argv) == 3 and sys.argv[1] in entryDict:
        update()
        sys.exit()


if __name__ == "__main__":
    main()

它按预期工作,直到我调用update()函数两次。换言之,只有在执行python3 file.py entryName valueHere两次操作时,才会出现JSONDecodeError。两次,因为根据程序,如果info.txt字典中已经存在条目名,则应该更新该条目。
为什么update()只工作一次,而不是两次?
错误:raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)指向主函数内的entryDict = json.load(entryFile)
我试过load/loads"r/w/a+"的不同变体。似乎什么都没用。我(主要)做错了什么

编辑:任何关于一般脚本/编程的提示/提示都将不胜感激


Tags: pathinfotxtjsonformatifoswith
1条回答
网友
1楼 · 发布于 2024-10-03 13:21:52

问题是在调用file.truncate(0)之后,不会将新内容写入文件的开头。从the docs

truncate(size=None)

Resize the stream to the given size in bytes (or the current position if size is not specified). The current stream position isn’t changed. This resizing can extend or reduce the current file size. In case of extension, the contents of the new file area depend on the platform (on most systems, additional bytes are zero-filled). The new file size is returned.

因此,在读取、截断和写入文件之后,文件的内容将有点像这样(其中\x00表示空字节):

\x00\x00\x00\x00\x00\x00\x00\x00{"key": "value"}

要解决此问题,请在entryFile.truncate(0)之后添加entryFile.seek(0)

相关问题 更多 >