Python 将最大编号的文件识别为文件名的一部分 [英] Python identify file with largest number as part of filename

查看:71
本文介绍了Python 将最大编号的文件识别为文件名的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文件末尾附加了一个数字,例如:

 file_01.csv文件_02.csv文件_03.csv

我正在寻找一种简单的方法来识别附加了最大数字的文件.有没有一种适度简单的方法来实现这一目标?...我正在考虑导入文件夹中的所有文件名,提取最后一位数字,转换为数字,然后寻找最大数字,但是对于我认为是一项相对常见的任务来说,这似乎有点复杂.

解决方案

如果文件名的格式真的很好,那么你可以简单地使用 max:

<预><代码>>>>max(['file_01.csv', 'file_02.csv', 'file_03.csv'])'file_03.csv'

但请注意:

<预><代码>>>>'file_5.csv' >'file_23.csv'真的>>>'my_file_01' >'文件_123'真的>>>'fyle_01' >'文件_42'真的

所以你可能想为你的函数添加某种验证,和/或使用 glob.glob:

<预><代码>>>>max(glob.glob('/tmp/file_??'))'/tmp/file_03'

I have files with a number appended at the end e.g:

  file_01.csv
  file_02.csv
  file_03.csv

I am looking for a simple way of identifying the file with the largest number appended to it. Is there a moderately simple way of achieving this? ... I was thinking of importing all file names in the folder, extracting the last digits, converting to number, and then looking for max number, however that seems moderately complicated for what I assume is a relatively common task.

解决方案

if the filenames are really formatted in such a nice way, then you can simply use max:

>>> max(['file_01.csv', 'file_02.csv', 'file_03.csv'])
'file_03.csv'

but note that:

>>> 'file_5.csv' > 'file_23.csv'
True
>>> 'my_file_01' > 'file_123'
True
>>> 'fyle_01' > 'file_42'
True

so you might want to add some kind of validation to your function, and/or or use glob.glob:

>>> max(glob.glob('/tmp/file_??'))
'/tmp/file_03'

这篇关于Python 将最大编号的文件识别为文件名的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆