如何在python中对以_开头的文件进行排序

时间:2015-07-14 21:56:20

标签: python

我在一个目录中有文件。

文件名很奇怪,其中一些以_开头,而另一些则以字母开头。

    _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?

2 个答案:

答案 0 :(得分:5)

假设您要忽略_,您可以将密钥中的words = ["_weight.txt","color.txt","_height.txt"] print(sorted(words, key=lambda x: x.lstrip("_"))) ['color.txt', '_height.txt', '_weight.txt'] lstrip至sorted / .sort以删除任何前导下划线:

files

不确定你要排序的是因为奇怪命名的directory实际上是一个字符串但是如果你想找到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("_"))) 中的所有html文件并排序那么你可以使用glob并对列表进行排序由glob返回:

https://fonts.googleapis.com/css?family=Open+Sans:400,800,700,600,300' rel='stylesheet' type='text/css' 

答案 1 :(得分:2)

您可以将key放入>>> sorted(filelist, key=lambda x: x[1:] if x.startswith('_') else x)

overflow: hidden