Python Script: Get the Filenames from a Directory

It’s sometimes really annoying having to get a list of file names and group them for use in an experiment. For example, when using a datasource in Experiment Builder, I often find myself needing to generate a line-by-line list of all of the image names in a given experiment. I’ve been using the Python script below to do it all for me. Saving the code below as a python file (something like names.py) means it’s a simple case of double-clicking the file to get what is needed.

import os
f = open('names.txt', 'w')

for root, dirs, files in os.walk('./'):
	for newname in files:
		filename = os.path.join(newname)
		newstring = filename + '\n'
		f.write(newstring)

This gives a file called “names.txt” which has a single line for each image in the directory (and all sub-directories). From the example above, I get:

names.py
names.txt
New Text Document - Copy (2).txt
New Text Document - Copy (3).txt
New Text Document - Copy (4).txt
New Text Document - Copy (5).txt
New Text Document - Copy (6).txt
New Text Document - Copy (7).txt
New Text Document - Copy.txt
New Text Document.txt

Note that this ends up including both the python script (names.py) and the output file (names.txt), so you’ll want to delete them before putting the list into Excel and doing funky stuff with it!

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.