繁体   English   中英

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

[英]How to sort files starting with _ in 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?

假设您想忽略_ ,则可以将键中的_剥离为sorted / .sort,以删除所有前划线。

words = ["_weight.txt","color.txt","_height.txt"]

print(sorted(words, key=lambda x: x.lstrip("_")))
['color.txt', '_height.txt', '_weight.txt']

不知道你正在排序为奇怪的命名files是实际的字符串,但如果你想找到的所有HTML文档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("_")))

您可以将_放入key

>>> sorted(filelist, key=lambda x: x[1:] if x.startswith('_') else x)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM