i have files in 1 directory.
the filenames weird, of starts _, while others start alphabet.
_weight.txt color.txt _height.txt i looking way sort alphabetically in python. know how sort alphabetically doesn't have idea files starting special characters such _.
can help?
so according replies, following code:
toolpath = os.path.dirname(os.path.abspath(__file__)) directory = os.listdir(toolpath) files in directory: if files.endswith(".html") sorted(files, key=lambda x:x.lstrip("_").lower()) htmlfile.write('<a href='+files+'>'+files+'</a><br>\n') at 1 place had sort txt files, worked. while in above code still doesn't print in alphabetical order. have 1 more question, filename example color.html, code writes html filename color.html. how can write color html page rather color.html?
presuming want ignore _, can lstrip _ in key sorted/.sort remove leading underscores:
words = ["_weight.txt","color.txt","_height.txt"] print(sorted(words, key=lambda x: x.lstrip("_"))) ['color.txt', '_height.txt', '_weight.txt'] not sure sorting strangely named files actual string if want find html files in directory , sort can use glob , sort list returned glob:
from glob import glob toolpath = os.path.dirname(os.path.abspath(__file__)) directory = os.listdir(os.path.join(toolpath,"*.html")) directory.sort( key=lambda x: x.lstrip("_")))
Comments
Post a Comment