pythonfilejarminecraft

Searching for a file name inside a folder of jar files


I had a problem while modding minecraft. Something added a c:coal tag to minecraft:charcoal, causing issues for me. So instead of opening each of my 200 .jar files in my mods folder, I made a quick script in Python 3.12.4 to search for the coal.json file inside the .jar files.

The problem I have is that the script does not seem to work. To be precise, the script runs and finds nothing. I even tested locating other common file names, like ores.json, but still told me that it found nothing.

Can someone tell me what is wrong with the script, or if there is an easier way to solve my original problem of locating the coal.json file?

Here is my script:

import os
import zipfile

# Define the path to the mods folder and the target file path
mods_folder = r"C:\Users\***\AppData\Roaming\PrismLauncher\instances\1.21\.minecraft\mods"
target_path = "data\\c\\tags\\item\\"
target_file = "coal.json"

# List to store the names of .jar files containing the target file
found_jar_files = []

# Iterate over all .jar files in the mods folder
for root, dirs, files in os.walk(mods_folder):
    for file in files:
        if file.endswith(".jar"):
            jar_path = os.path.join(root, file)
            
            try:
                # Open the .jar file as a zip archive
                with zipfile.ZipFile(jar_path, 'r') as jar:
                    # Check if the target path and file exists in the .jar archive
                    for entry in jar.namelist():
                        # Check if the entry matches the target path and file
                        if entry == f"{target_path}{target_file}":
                            print(f"Found '{target_file}' in: {jar_path}")
                            found_jar_files.append(jar_path)
                            break  # Stop checking further entries in this .jar
            except zipfile.BadZipFile:
                print(f"Error: {jar_path} is not a valid .jar file.")

# Print results
if found_jar_files:
    print(f"\nThe following .jar files contain '{target_file}':")
    for jar_file in found_jar_files:
        print(jar_file)
else:
    print(f"No '{target_file}' found in any .jar files in the folder: {mods_folder}")

Solution

  • Just edited so target_path = "data/c/tags/item/" # Ensure forward slashes are used

    now, it will match with what jar.namelist() generates