[Python] Traverse all JSON files under the specified path

Traverse all JSON files under the specified path

Python is a powerful and flexible programming language, and by using its built-in os and json modules, we can easily process JSON files. This tutorial will guide you step by step to learn how to traverse all JSON files under a specified path, and demonstrate how to open, parse, and process these JSON data.

Step 1: Prepare the Python environment

First, make sure Python is installed on your computer. You can download and install the latest version of Python fromPython official website.

Step 2: Create Python Script

Open your favorite text editor (such as VSCode, Sublime Text, etc.) and create a new Python script file. Copy and paste the following code into the file:

import os
import json

def read_json_files_in_directory(directory_path):
    # 确保路径存在
    if not os.path.exists(directory_path):
        print(f"指定的路径 '{
      
      directory_path}' 不存在")
        return

    # 遍历目录中的所有文件
    for filename in os.listdir(directory_path):
        filepath = os.path.join(directory_path, filename)

        # 检查文件是否是JSON文件
        if filename.endswith('.json'):
            print(f"正在读取文件: {
      
      filename}")

            # 打开并读取JSON文件
            with open(filepath, 'r', encoding='utf-8') as file:
                try:
                    # 解析JSON数据
                    json_data = json.load(file)
                    
                    # 在这里处理你的JSON数据,可以根据需求进行操作

                    # 例如,打印JSON数据
                    print(json_data)

                except json.JSONDecodeError as e:
                    print(f"解析JSON文件 '{
      
      filename}' 时出错: {
      
      e}")

# 指定路径,替换成你的路径
directory_path = '/path/to/your/json/files'

# 调用函数,读取指定路径下的所有JSON文件
read_json_files_in_directory(directory_path)

Make sure to replace/path/to/your/json/files with the path to your actual JSON file.

Step 3: Run the script

Save your script file, then open a command line or terminal and enter the directory where the script file is located. Run the following command:

python your_script_name.py

Replaceyour_script_name.py with the actual name of your script file. After running the script, you will see that the script reads and prints the contents of all JSON files under the specified path one by one.

in conclusion

Through this simple yet detailed tutorial, you learned how to use Python to traverse all JSON files under a specified path. This is the foundation for processing large-scale JSON data, and you can build more complex data processing and analysis tools on top of it. Hope this tutorial helps you on your learning journey!

Guess you like

Origin blog.csdn.net/linjiuxiansheng/article/details/135010454