Noob alert - sort output with python


#1

Advanced apologize for my complete lack of knowledge here, I’ve been working through this with google and crtl-c crtl-v.
I have a small script to watch a folder for 3dm files and output the filenames to another grasshopper component, how can I sort the list of files either numerically or alphabetically.

this is what I have so far to watch the folder.

import os
for root, dirs, files in os.walk(y):
    for file in files:
        if file.endswith(".3dm"):
             print(os.path.splitext(file)[0])

I’m assuming I need to use sort() to get the result I want but don’t know how to actually apply it here.


(Willem Derks) #2

Hi,

First of all no need to apologise there’s no such thing as stupid questions they’re only stupid answers.

In order to sort a list of files what you will need to do is collect the filenames in a list that you can later on sort.

import os

filenames = [] #create empty list

for root, dirs, files in os.walk(y):
    for file in files:
        if file.endswith(".3dm"):
             #add to the list
             filenames.append(os.path.splitext(file)[0])


#you now have a list of all de filenames you can sort.
print filenames
filenames.sort()
print filenames

I’m on my phone so I might have made a mistake but you probably get the gist of it. Good luck and report back if you have any more questions.
-Willem