Script for convert many OBJs to .blend files

I have files structure like this one:

.
└── Environment
    ├── aa
    │   ├── aa
    │   │   ├── 1.tga
    │   │   └── 2.tga
    │   ├── aa.obj
    │   └── aa.mtl (with map_Kd links to ./aa/1(2).tga)
    ├── ab ... (other folders with similar structure)

So I need to create .blend file for each obj-mtl pair through command-line script that should be located in top-level folder (Environment). Ideally, this new blend file must be at the same level with obj and mtl (aa.blend). Manually I was imported files with default options, except splitting: by group, not by object.

By the way I did this task before manually, with many models… And then I found out that Bleder has API for doing stuff through Python scripts :roll_eyes: But I’m noobie at Python, Blender API (and generally in the Blender too).

If it matters I’ve use 2.82a at Linux Mint 19.2 64bit

##################################################
## Create .blend files from .obj and .mtl files.
## Processing was performed through Blender API.
##
## Requirements:
## 1. Blender (tested on Blender 2.82 (sub 7))
## 2. Script not tested on Windows (maybe only Linux-specific)
##
## How to use:
## 1. Put this script to the top-level in files structure like this
##  ├── aa
##  │   ├── aa
##  │   │   ├── 1.tga
##  │   │   └── 2.tga
##  │   ├── aa.obj
##  │   └── aa.mtl (with map_Kd links to ./aa/1(2).tga)
##  ├── ab ... (other folders with similar structure)
## 2. Run script via Blender:
## Examples:
## path-to-blender-executable/blender --background --python create-blend-files.py
## flatpak run org.blender.Blender/x86_64/stable --background --python create-blend-files.py
##
##################################################

import bpy
import os

print("________")

current_dir = os.path.dirname(os.path.abspath(__file__))

dir_items = sorted(os.listdir(current_dir))
dirs = [item for item in dir_items if os.path.isdir(item)]
for dir in dirs:
    # skip "hidden" dirs
    if dir.startswith('.'):
        continue

    file_list = sorted(os.listdir(dir))
    obj_list = [item for item in file_list if item.endswith('.obj')]
    for item in obj_list:
        obj_file_path = os.path.join(dir, item)

        bpy.ops.import_scene.obj(filepath=obj_file_path, use_split_objects=False, use_split_groups=True)
        blend_file_path = os.path.splitext(os.path.abspath(obj_file_path))[0] + '.blend'

        # remove .blend file if already exists
        try:
            os.remove(blend_file_path)
        except OSError:
            pass

        bpy.ops.wm.save_as_mainfile(filepath=blend_file_path)
        bpy.ops.object.delete(use_global=False)

print("========")