The eBook Shuffle

Remember when there were mini mp3 players with one button and a shuffle feature? If like many geeks you have a bunch of interesting ebooks from Humble Bundle, Oreilly or Github or wherever you get technical books, you probably have folders and folders of lots of interesting books. What if you want to “shuffle” or randomly pick one off your virtual bookshelf and read a bit while staying home? Today I’ll show how to virtually “grab a book off the shelf” of your collection with a simple Python script:

os.walk

Os.walk is a powerful listing command in Python. Start a basic listing script like so:

#!/usr/bin/env python3
import os
def main(args):
    for dirpath, dirnames, filenames in os.walk('.'):
        print('Directories in %s:' % (dirpath,))
        for dir in dirnames:
            print(os.path.join(dirpath,dir))
        print('Files in %s:' % (dirpath,))
        for filename in filenames:
            print(os.path.join(dirpath,filename))
    return 0

if __name__ == '__main__':
    import sys
    sys.exit(main(sys.argv))

Run this to list out the contents of the current working directory (“.”). So to choose some random file that has .epub or .pdf, let’s first make an array of all such files:

#!/usr/bin/env python3
import os

def allbooks(path):
    types = ['.epub','.pdf']
    paths = []
    for dirpath, dirnames, filenames in os.walk(path):
        for filename in filenames:
            for t in types:
                if filename.lower().endswith(t):
                    paths.append(os.path.join(dirpath,filename))
    return paths

def main(args):
    print(str(len(allbooks('.'))) + ' books!')
    return 0

if __name__ == '__main__':
    import sys
    sys.exit(main(sys.argv))

Cool, this counts how many ebooks in your collection! You can choose one with random.choice([array])… and the “xdg-open (path)” should open the file with your preferred application on Linux:

#!/usr/bin/env python3
import os
import random

def allbooks(path):
    types = ['.epub','.pdf']
    paths = []
    for dirpath, dirnames, filenames in os.walk(path):
        for filename in filenames:
            for t in types:
                if filename.lower().endswith(t):
                    paths.append(os.path.join(dirpath,filename))
    return paths

def main(args):
    all = allbooks('.')
    print(str(len(all)) + ' books!')
    book = random.choice(all)
    print(book)
    os.system("xdg-open '"+book+"'")
    return 0

if __name__ == '__main__':
    import sys
    sys.exit(main(sys.argv))

Leave a Reply

Your email address will not be published. Required fields are marked *

× three = thirty