如何制作按时间顺序排列的文件列表,并包含文件修改日期
我想在扩展名为 .bas 的目录中创建这些文件的列表,这些文件是在 2011 年 6 月 1 日之后修改的。另外,我想知道如何选择性地让列表中的文件显示日期以及文件上次修改的时间,例如“filename.bas 2011-06-04_AM.00.30”
我是 python 新手。我能够使用以下代码列出具有 .bas 扩展名的文件,并按日期排序:
from stat import S_ISREG, ST_CTIME, ST_MODE
import os, sys, time, glob
search_dir = r"e:\test"
files = filter(os.path.isfile, glob.glob(search_dir + "\\*.bas"))
files.sort(key=lambda x: os.path.getmtime(x))
但我不知道如何将“日期”附加到列表中的文件名。
任何建议将不胜感激。
I want to create a list of those files in a directory which have the extension .bas, and which were modified after June 1, 2011. Also, I'd like to know how to optionally have the files in the list appear with the date and time the file was last modified, e.g., 'filename.bas 2011-06-04_AM.00.30'
I am a python newbie. I was able to list files having the .bas extension, sorted by date, by using the following code:
from stat import S_ISREG, ST_CTIME, ST_MODE
import os, sys, time, glob
search_dir = r"e:\test"
files = filter(os.path.isfile, glob.glob(search_dir + "\\*.bas"))
files.sort(key=lambda x: os.path.getmtime(x))
But I can't figure out how to append " date" to the filename in the list.
Any suggestions would be very much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将文件和日期收集到元组列表中,并按日期元素对该列表进行排序。这是示例代码,其中的注释应该足以理解它:
(可选)您可以使用列表理解使代码更加紧凑和干净...
这两行将替换所有
for
从第一个示例开始循环。现在,如果您在列表中想要的是一个带有文件名和日期格式的字符串,那么...添加此导入...
以及具有此列表理解的另一行,该列表理解获取修改时间戳并将其格式化为字符串。
要反转排序顺序,请在
sort
执行中使用可选参数reverse
:将日期限制为特定的
datetime
如您所见您可以在列表理解中添加一个
if
条件,这真的很酷。Collect files and dates in a list of tuples and sort that list by the date element. Here is the example code, the comments in it should be sufficient to understand it:
Optionally, you can use a list comprehension to make the code more compact and clean ...
This two lines would replace all the
for
loop from the first example.Now if what you want in the list is a string with filename and date formatted then ... add this import ...
and another line with this list comprehension that takes the modification time stamp and formats it into a string.
For reversing the order of the sort use the optional parameter
reverse
in thesort
execution:For limiting the date to a specific
datetime
As you can see you can add an
if
condition inside the list comprehension, which is really cool.