gpt4 book ai didi

python 对文件的扩展名/名称进行排序

转载 作者:太空宇宙 更新时间:2023-11-03 17:44:36 26 4
gpt4 key购买 nike

我正在为一个学校项目编写脚本:

search_folder = raw_input('Choose Directory')

for root, dirs, files in os.walk(search_folder):
for file in files:
pathname = os.path.join(root, file)
print pathname
print os.path.getsize(pathname)

如何对扩展上的输出进行排序?

最佳答案

对文件名进行排序

使用sorted()os.path.splitext() lambdasort-by key 参数中。

示例

import os

search_folder = '/Users/temp/'

results = []
for root, dirs, files in os.walk(search_folder):
for f in files:
results.append(os.path.join(root, f))

sorted_results = sorted(results, key=lambda x: os.path.splitext(x)[1])

for path in sorted_results:
print path
print os.path.getsize(path)
<小时/>
/Users/temp/.DS_Store
6148
/Users/temp/.localized
0
/Users/temp/profile.png
81168
/Users/temp/IMG_0115.xcf
113212
/Users/temp/profile.xcf
535202

其他注意事项和建议

使用 list comprehension

您还可以使用list comprehension (为了速度和可读性)遍历文件:

results = [os.path.join(root, f) 
for root, dirs, files in os.walk(search_folder)
for f in files]

内存高效排序

排序而不存储suggestion来自@PM2Ring:

for root, dirs, files in os.walk(search_folder):
for f in sorted(files, key=lambda x: tuple(reversed(os.path.splitext(x)))):
pathname = os.path.join(root, f)
print pathname
print os.path.getsize(pathname)

关于python 对文件的扩展名/名称进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30003624/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com