You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复Python代码中IOError: [Errno 2] data.json文件不存在错误?

Fixing "IOError: [Errno 2] No such file or directory: 'data.json'"

Hey there, that error means Python can't locate your data.json file where it's expecting to find it. Let's walk through the most straightforward fixes to get your script up and running:

1. Place data.json in the same folder as your Python script

This is the quickest fix. Just check the directory where you saved your .py file, then move the data.json file directly into that exact folder. By default, Python looks for files in the same directory as the script when you use a relative path like "data.json", so this should resolve the error right away.

2. Use an absolute file path if the JSON file is in another location

If you want to keep data.json in a separate folder (like a dedicated resources directory), you can use the full absolute path to the file. Here are examples for different operating systems:

# Windows example
data = json.load(open("C:/Users/YourUsername/Documents/MyProject/data.json"))

# macOS/Linux example
data = json.load(open("/home/YourUsername/Documents/MyProject/data.json"))

For a more robust, cross-platform solution, use Python's os module to build the path automatically (so it works no matter where you move your script and JSON file, as long as they stay paired):

import os
import json

# Get the folder where your script is stored
script_directory = os.path.dirname(os.path.abspath(__file__))
# Build the full path to data.json
json_file_path = os.path.join(script_directory, "data.json")
data = json.load(open(json_file_path))

3. Double-check the file name for typos

It's easy to overlook, but small mistakes here can cause big issues:

  • Make sure the file is named exactly data.json (no uppercase letters like Data.json, extra spaces, or misspellings like dat.json).
  • On Windows, file extensions are often hidden by default. Go to File Explorer > View > check "File name extensions" to confirm the file isn't just named data (with the .json extension hidden).

4. Verify Python's current working directory

If none of the above works, add these lines at the start of your script to see where Python is actively searching for files:

import os
print("Python is looking for files in this folder:", os.getcwd())

Once you see that path, either move data.json into that directory or update your script's file path to point to the JSON file's actual location.


内容的提问来源于stack exchange,提问作者Ragulan V

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:42:42