I have no idea where to start with this, a few pointers and a kick in the right direction would be much appreciated.

I run a radio station. All our music is in folders representing music styles. From time to time I want to print out a complete library. Printing folder at a time is fine but I end up with 12 printouts, I would rather have one print out with all the contents of the 12 folders combined and arranged alphabetically. The folders rarely change names etc so could be hard-coded or I may write a gui for their individual selection later.

Its the reading of folders contents and combining them I am stuck on...

Please.

This is on a windows XP system (with Python 2.7)

Dani AI

Generated

: building on 's directory-traversal hint, a simple, practical approach is to walk each folder, collect matching files, deduplicate, sort case-insensitively, and write a single text file you can print. The example below is ready to paste into a Python interpreter and tweak the FOLDERS and EXTS lists.

import os
import codecs

FOLDERS = [
    u"C:\\Radio\\Music\\Jazz",
    u"C:\\Radio\\Music\\Rock",
    u"C:\\Radio\\Music\\Classical",
    # add the rest
]

EXTS = set([u".mp3", u".wav", u".flac", u".ogg", u".m4a", u".wma"])

found = set()
for folder in FOLDERS:
    for dirpath, dirnames, filenames in os.walk(folder):
        for fn in filenames:
            if os.path.splitext(fn)[1].lower() in EXTS:
                found.add(fn)         # use os.path.join(dirpath, fn) to keep full paths

sorted_list = sorted(found, key=lambda s: s.lower())

out_file = u"C:\\temp\\library_list.txt"
with codecs.open(out_file, "w", "utf-8-sig") as out:
    for name in sorted_list:
        out.write(name + u"\r\n")

try:
    os.startfile(out_file, "print")
except Exception:
    pass

Notes and tweaks: store full paths instead of basenames if you need folder context; preserve folder grouping by prefixing each name with the containing folder; add or remove extensions in EXTS. Prefixing literal folder strings with u helps the walk return unicode names so writing with codecs.open(..., "utf-8-sig") produces a BOM that old editors recognize. If Notepad displays garbled characters, try opening the output in Notepad++ or change the encoding to cp1252.

Troubleshooting: permission errors mean run with appropriate rights; extremely long paths can hit Windows path-length limits; os.startfile(..., "print") uses the file association for printing (may behave differently depending on default editor). See the Python docs for details on walking directories and file I/O: os.walk documentation, codecs.open documentation, os.startfile documentation.

Recommended Answers

All 2 Replies

use os.listdir and os.path.isdir

Thanks pytony, that's a starting point...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.