Search code examples
pythonpython-3.xminecraft

Edit Minecraft .dat File in Python


I'm looking to edit a Minecraft Windows 10 level.dat file in python. I've tried using the package nbt and pyanvil but get the error OSError: Not a gzipped file. If I print open("level.dat", "rb").read() I get a lot of nonsensical data. It seems like it needs to be decoded somehow, but I don't know what decoding it needs. How can I open (and ideally edit) one of these files?


Solution

  • To read data just do :

    from nbt import nbt
    
    nbtfile = nbt.NBTFile("level.dat", 'rb')
    print(nbtfile) # Here you should get a TAG_Compound('Data')
    print(nbtfile["Data"].tag_info()) # Data came from the line above
    for tag in nbtfile["Data"].tags: # This loop will show us each entry 
        print(tag.tag_info())
    

    As for editing :

    # Writing data (changing the difficulty value
    nbtfile["Data"]["Difficulty"].value = 2
    print(nbtfile["Data"]["Difficulty"].tag_info())
    nbtfile.write_file("level.dat")
    

    EDIT:

    It looks like Mojang doesn't use the same formatting for Java and bedrock, as bedrock's level.dat file is stored in little endian format and uses non-compressed UTF-8. As an alternative, Amulet-Nbt is supposed to be a Python library written in Cython for reading and editing NBT files (supposedly works with Bedrock too). Nbtlib also seems to work, as long as you set byteorder="little when loading the file.

    Let me know if u need more help...