如何用json存储python文件?

问题描述 投票:0回答:2

对于我的编程课,我想编写一个可以访问该游戏之前运行的分数的代码。我从这个网站找到了一些信息(特别是来自@olinox14。任何与 JSON 相关的代码片段都来自他们)。这是我到目前为止所拥有的:

import random
import json

i = True
while i == True:

    score_file = r"/pat/to/score/file.json"
    try:
        with open(score_file, 'r') as f:
            scores = json.load(f)
    except FileNotFoundError:
        scores = {}

    user_name = input("What's your username?")
    print("Let's play a guessing game! I'll think of a number between two numbers of your choice, and you'll have to guess it. I'll tell you when you're close!")
    min = int(input("What do you want the minimum to be?"))
    limit = int(input("What do you want the limit to be?"))

    random_number = random.randint(min, limit )
    user_number = int(input("Give me a number between " + str(min) + " and " + str(limit) + "."))
    score = 1

    while user_number != random_number:
        if random_number < user_number:
            print("Think lower! Let's try again.")
        if random_number > user_number:
            print("Think higher! Let's try again.")
        if user_number < min or user_number > limit:
            print("That's not between " + str(min) + " and " + str(limit) + "!")
        if user_number == random_number + 2 or user_number == random_number - 2:
            print("You're getting closer! Your guess is just two away.")
        if user_number == random_number + 1 or user_number == random_number - 1:
            print("You're very close; just one away!")
        user_number = int(input("Give me a number between 1 and " + str(limit) + "."))
        score = score + 1

    while user_number == random_number:
        scores[user_name] = score
        print("Congratulations! You guessed it!")

        print("You guessed it in " + str(score) + " tries.")
        if score == 1:
            print("You guessed it in 1 try. Good job!")
        break

    while True:
        go_again = input("Would you like to go again? Type yes or no.")
        if go_again == "yes":
            print("Good luck!")
            break
        elif go_again == "no":
            print("Goodbye!")
            i = False
            break
        else:
            print("You didn't type yes or no! Please try again.")
with open(score_file, 'w+') as f:
    json.dump(scores, f)
scores_sorted = sorted([(p, s) for p, s in scores.items()], reverse=True, key=lambda x: x[1])
for player, score in scores_sorted:
    print(player, score)

我真的不知道这是如何工作的,也不知道我应该如何修复它。每当程序到达最后一部分时,我都会收到此错误:

Traceback (most recent call last):
Grade\Python\number game.py", line 62, in <module>
    with open(score_file, 'w+') as f:
         ^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: '/pat/to/score/file.json'

我不知道这意味着什么。请解释如何解决这个问题,就像你在和一个五岁的孩子说话一样。

python json
2个回答
0
投票

您遇到了错误,因为程序在您的计算机上找不到文件

'/pat/to/score/file.json'
。这通常意味着以下两件事之一:

  1. 文件路径不正确。您可能输入错误,或者您指定的位置确实不存在该文件。
  2. 目录(文件夹)不存在。如果文件所在的文件夹不存在,Python不会自动创建它,并会抛出一个
    FileNotFoundError

以下是如何逐步解决这些问题:

第 1 步:检查路径

您在代码中使用的路径是

'/pat/to/score/file.json'
。这看起来像一个占位符路径。您需要将其替换为您想要存储分数文件的实际路径。例如,如果您使用的是 Windows 计算机,并且想要将乐谱存储在“文档”文件夹中,您的路径可能类似于:

score_file = 'C:/Users/YourUsername/Documents/score_file.json'

YourUsername
更改为您计算机上的实际用户名。

如果您使用的是 Mac 或 Linux,它可能看起来像:

score_file = '/Users/YourUsername/Documents/score_file.json'

第2步:确保目录存在

确保要保存文件的文件夹确实存在。在上面的示例中,您需要有一个可供使用的文档文件夹。如果不存在,您可以通过文件资源管理器手动创建它,或者如果不存在,您可以修改程序来创建它。

第 3 步:根据需要修改代码以创建目录

您可以修改 Python 脚本以自动创建该目录(如果该目录不存在)。具体方法如下:

  1. 导入
    os
    模块,它允许您与操作系统交互。
  2. 在尝试打开文件之前,请检查该目录是否存在,如果不存在,则创建它。

以下是如何执行此操作的示例:

import os  # Add this at the beginning of your file

# Check if the directory exists before opening the file
dir_name = os.path.dirname(score_file)
if not os.path.exists(dir_name):
    os.makedirs(dir_name)

# Now, you can safely open your file
with open(score_file, 'w+') as f:
    json.dump(scores, f)

最后注意事项

这些步骤将确保您的程序可以找到并写入文件,而不会遇到

FileNotFoundError
。确保路径的每个部分都正确,包括文件名和目录名。另外,如果您使用的是 Mac 或 Linux,请记住在路径中使用正斜杠
/
;如果您使用的是 Windows,请记住在路径中使用正斜杠
/
或双反斜杠
\\
(Python 使用反斜杠
\
作为转义)字符,因此您需要在字符串中将它们加倍以表示文件路径中的实际反斜杠)。


0
投票

在文件的开头

score_file = r"/pat/to/score/file.json"

应将其更改为计算机上文件所在的位置。要么将其更改为您想要存储它的位置,要么简单地将其更改为

score_file = r"file.json"

如果你想将文件存放在python脚本所在的文件夹中

© www.soinside.com 2019 - 2024. All rights reserved.