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 torrentls.py 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 torrentls.py <torrent file>. torrentls.py is argparse-based so it provides a built-in help. Additionally, you can use it as library for basic parsing of torrent files.

torrentls.py 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__ = "ukoehler@techoverflow.net"
__status__ = "Development"

def listTorrent(filename):
    "List file paths within a single torrent"
    with open(filename, "rb") as fin:
        torrent = bencode.bdecode(fin.read())
        #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):
        print(filename)