Listing files inside a Torrent

Mi 31 Dezember 2014
By Uli Köhler

In Python

Torrent files are essentially containers that store information about a set of files to be downloaded via P2P.

Unfortunately it is not easily possible to simply list the files that are stored in a torrent. Using our python script you can easily accomplish that task.

Start by installing the dependencies

sudo pip install bencode

After that, you can easily execute the script using a shell command like python <torrent file>. is argparse-based so it provides a built-in help. Additionally, you can use it as library for basic parsing of torrent files. download
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import bencode
import itertools

__author__ = "Uli Koehler"
__copyright__ = "Copyright 2014 Uli Koehler"
__license__ = "Apache License v2.0"
__version__ = "0.1"
__maintainer__ = "Uli Koehler"
__email__ = ""
__status__ = "Development"

def listTorrent(filename):
    "List file paths within a single torrent"
    with open(filename, "rb") as fin:
        torrent = bencode.bdecode(
        #While the path element is usually a single-element list, we support arbitrary length
        return itertools.chain(*(f["path"] for f in torrent["info"]["files"]))

if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser(description="List the filenames in a torrent file")
    parser.add_argument("torrent", help="The torrent file to print")
    args = parser.parse_args()
    #Print files in torrent, one per line
    for filename in listTorrent(args.torrent):