[英]python sort on extension / Name of the file
I'm working on a script for a school project: 我正在为学校项目编写脚本:
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)
How can I sort the output on Extension? 如何在Extension上对输出进行排序?
Use sorted()
with an os.path.splitext()
lambda in the sort-by key
parameter. 在sort-by
key
参数中将sorted()
与os.path.splitext()
lambda一起使用。
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
You can also use list comprehension (for speed and readability) to walk the files: 您还可以使用列表理解 (为了提高速度和可读性)遍历文件:
results = [os.path.join(root, f)
for root, dirs, files in os.walk(search_folder)
for f in files]
Sort without storing suggestion from @PM2Ring: 排序时不存储来自@ 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.