Python如何遍历文件夹读取JSON文件,解决读取时的TypeError报错问题
问题原因及修复方案
现有代码的核心错误
- 错误1:
open()函数传入了列表类型参数:报错信息对应的写法是直接把json_files整个列表传给了open(),该函数仅接受字符串格式的单个文件路径 - 错误2:缺少完整路径拼接:
os.listdir()仅返回文件名,未携带父级目录路径,直接用文件名打开会触发文件不存在报错 - 错误3:
open()第二个参数误用:第二个参数是文件打开模式,你错误传入了json模块对象,正确读模式应为'r'或者留空使用默认值
修复后完整代码(含新增/更新文件监测功能)
import os import json import time # 配置参数 path_to_json = '/Webservertesting/JsonFiles' # 记录已处理文件的最后修改时间,用于检测更新 processed_files = {} def scan_json_files(): # 获取目录下所有json文件的完整路径 json_files = [] for filename in os.listdir(path_to_json): if filename.endswith('.json'): full_path = os.path.join(path_to_json, filename) json_files.append(full_path) return json_files if __name__ == '__main__': # 首次扫描处理现有文件 print("首次扫描现有JSON文件:") for file_path in scan_json_files(): mtime = os.path.getmtime(file_path) processed_files[file_path] = mtime # 读取打印文件内容 with open(file_path, 'r', encoding='utf-8') as f: try: data = json.load(f) print(f"\n文件 {os.path.basename(file_path)} 内容:") print(data) except json.JSONDecodeError: print(f"\n文件 {os.path.basename(file_path)} 不是合法JSON格式,跳过") # 循环监测新增/更新文件,间隔5秒扫描一次 print("\n开始监测文件变化,按Ctrl+C退出...") while True: current_files = scan_json_files() # 检查新增或更新的文件 for file_path in current_files: current_mtime = os.path.getmtime(file_path) if file_path not in processed_files: # 新增文件 print(f"\n检测到新增JSON文件:{os.path.basename(file_path)}") with open(file_path, 'r', encoding='utf-8') as f: try: data = json.load(f) print("文件内容:") print(data) except json.JSONDecodeError: print("文件不是合法JSON格式,跳过") processed_files[file_path] = current_mtime elif current_mtime > processed_files[file_path]: # 文件已更新 print(f"\n检测到JSON文件更新:{os.path.basename(file_path)}") with open(file_path, 'r', encoding='utf-8') as f: try: data = json.load(f) print("更新后内容:") print(data) except json.JSONDecodeError: print("文件不是合法JSON格式,跳过") processed_files[file_path] = current_mtime # 等待后再次扫描 time.sleep(5)
代码说明
- 用
os.path.join()拼接父路径和文件名,得到完整的文件路径,避免文件找不到的问题 - 新增了
processed_files字典记录每个文件的最后修改时间,每次扫描对比时间戳即可识别新增、更新的文件 - 增加了
JSONDecodeError异常捕获,避免遇到格式错误的JSON文件导致程序崩溃 - 扫描间隔可自行修改
time.sleep()的参数,单位为秒
内容的提问来源于stack exchange,提问作者La Brewers
相关产品推荐
相关产品推荐

