im writing a function to return a random file in a directory, also – i want to be able to match a substring in the file name.
def get_rand_file(folder, match=None):
if match == None:
return random.choice(os.listdir(folder))
else:
matching = []
for s in os.listdir(folder):
if match in s:
matching.append(s)
return random.choice(matching)
this code will work, but i am working with LOTS of files and this code takes a while, i tried doing it with list comprehension and mapping and i couldn’t make it work. any suggestions?
Documentation on list comprehensions :
http://docs.python.org/tutorial/datastructures.html#list-comprehensions