python - 如何对包含数字的 glob.glob 进行排序?
问题描述
正在做
glob.glob('/var/log/apache2/other_vhosts_access.log*')
给出一个未排序的列表,例如['....76.gz', '....16.gz', '....46.gz', ...]
. 还,
sorted(glob.glob('/var/log/apache2/other_vhosts_access.log*'))
给
other_vhosts_access.log
other_vhosts_access.log.1
other_vhosts_access.log.10.gz
other_vhosts_access.log.11.gz
other_vhosts_access.log.12.gz
...
other_vhosts_access.log.19.gz
other_vhosts_access.log.2.gz
如何有更好的排序? .log, .log.1, .log.2.gz, ..., .log.9.gz, .log.10.gz, ...
解决方案
为了扩展我的评论,也许这样的事情会做。这会提取在小数点之间或文件末尾找到的第一个数字序列,并将该值用作主排序键,并将完整文件名用作辅助键。
file_list = """
other_vhosts_access.log
other_vhosts_access.log.1
other_vhosts_access.log.10.gz
other_vhosts_access.log.11.gz
other_vhosts_access.log.12.gz
other_vhosts_access.log.19.gz
other_vhosts_access.log.2.gz
""".strip().split()
import re
re_num = r"\.(\d+)(\.|$)"
def sort_key(file_name):
match=re.search(re_num,file_name)
if match is None:
return(0,file_name)
else:
return(int(match.group(1)),file_name)
print(*sorted(file_list,key=sort_key),sep='\n')
推荐阅读
- android - CardView 权重与 ImageView
- excel - SharePoint 列表中两个日期和时间之间的差异
- linux - 为什么 ld.so 是共享对象?
- reactjs - 如何使用 React 和 Yup 验证(没有 Formik)
- python - 带有 grep 的 Git Python 日志
- node.js - How to fix this error UnhandledPromiseRejectionWarning: TypeError [ERR_UNESCAPED_CHARACTERS]:
- c++ - 如何将 shared_ptr 动态存储在 shared_ptr 中?
- java - Appium 找不到“adb.exe”
- ruby-on-rails - session#destroy 未应用
- c++ - Visual C++ static initializer strange behavior