我在一个目录里有文件。
文件名很奇怪,其中一些以_开头,另一些以字母表开头。
_weight.txt
color.txt
_height.txt我正在寻找在python中按字母顺序排序的方法。我知道如何按字母顺序排序,但不知道以特殊字符(如_ )开头的文件。
有人能帮忙吗?
因此,根据答复,以下是我的代码:
toolpath = os.path.dirname(os.path.abspath(__file__))
directory = os.listdir(toolpath)
for files in directory:
if files.endswith(".html")
sorted(files, key=lambda x:x.lstrip("_").lower())
htmlfile.write('<a href='+files+'>'+files+'</a><br>\n') 在我不得不对txt文件进行排序的地方,它起了作用。虽然在上面的代码中,它仍然没有按字母顺序打印。我还有一个问题,例如,文件名是color.html,因此我的代码写到html文件名color.html。如何才能只将颜色写到html页面而不是color.html?
发布于 2015-07-14 21:59:44
假设您想忽略_,可以在排序/..sort键中删除_,以删除任何前导下划线:
words = ["_weight.txt","color.txt","_height.txt"]
print(sorted(words, key=lambda x: x.lstrip("_")))
['color.txt', '_height.txt', '_weight.txt']不确定您正在排序的是什么,因为名称奇怪的files实际上是一个字符串,但是如果您希望在directory中找到所有的html文件并进行排序,那么您可以使用glob并对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("_")))发布于 2015-07-14 22:00:00
您可以将_放到key中。
>>> sorted(filelist, key=lambda x: x[1:] if x.startswith('_') else x)https://stackoverflow.com/questions/31418085
复制相似问题