【问题标题】:Python: sort files by datetime in more detailsPython:更详细地按日期时间对文件进行排序
【发布时间】:2012-06-08 06:11:35
【问题描述】:

我在 ubuntu 中使用 python 2.7。我如何以更详细的顺序对文件进行排序,因为我有一个脚本可以在几秒钟内创建成 txt 苍蝇的数量。我有一个脚本,它可以找到最旧和最年轻的文件,但它似乎只是与第二个而不是毫秒比较。

我的打印输出:

output_04.txt                     06/08/12 12:00:18
output_05.txt                     06/08/12 12:00:18

-----------
oldest: output_05.txt    
youngest: output_05.txt
-----------

但最旧文件的正确顺序应该是“output_04.txt”。 有专业知道吗?谢谢!

更新: 感谢大家。 我确实尝试了所有代码,但似乎没有我需要的输出。 对不起,伙计们,我确实很感谢你们。但是我上面的文件示例具有相同的时间,因此如果完整日期,小时,分钟,秒都相同,则必须以毫秒为单位进行比较。不是吗?如果我错了纠正我。感谢大家!干杯!

【问题讨论】:

标签: python ubuntu python-2.7


【解决方案1】:

您可以使用os.path.getmtime(path_to_file)获取文件的修改时间。

排序文件列表的一种方法是使用os.listdir 创建它们的列表并获取每个文件的修改时间。您将有一个元组列表,您可以按元组的第二个元素(即修改时间)对其进行排序。

您也可以使用os.stat_float_times() 查看os.path.getmtime 的分辨率。如果后者返回 True 则 os.path.getmtime 返回一个浮点数(这表明您的分辨率超过秒数)。

【讨论】:

  • files.sort(key=lambda f: os.path.getmtime(os.path.join(path, f)))
【解决方案2】:
def get_files(path):
    import os
    if os.path.exists(path):
        os.chdir(path)
        files = (os.listdir(path))
        items = {}
        def get_file_details(f):
            return {f:os.path.getmtime(f)}
        results = [get_file_details(f) for f in files]
        for result in results:
            for key, value in result.items():
                items[key] = value
    return items

v = sorted(get_files(path), key=r.get)

get_filespath 作为参数,如果path 存在,则将当前目录更改为路径并生成文件列表。 get_file_details 产生文件的最后修改时间。

get_files 返回一个以文件名为键、修改时间为值的字典。然后标准sorted 用于对值进行排序。可以传递reverse 参数进行升序或降序排序。

【讨论】:

  • 如何定义该路径是否存在?抱歉,我是 python 新手。
  • path = '/home/jack' 然后调用 v = sorted(get_files(path), key=r.get)
【解决方案3】:

您无法比较毫秒,因为没有此类信息。

stat(2) 调用返回三个 time_t 字段: - 访问时间 - 创建时间 - 上次修改时间

time_t 是一个整数,表示自 1970 年 1 月 1 日 00:00 UTC 以来经过的秒数(不是毫秒)。

因此,您可以在文件时间中获得的最大细节是秒。我不知道某些文件系统是否提供了更高的分辨率,但是您必须在 C 中使用特定的调用,然后在 Python 中编写包装器才能使用它们。

【讨论】:

    【解决方案4】:

    你好试试下面的代码

    # retrieve the file information from a selected folder
    # sort the files by last modified date/time and display in order newest file first
    # tested with Python24    vegaseat    21jan2006
    import os, glob, time
    # use a folder you have ...
    root = 'D:\\Zz1\\Cartoons\\' # one specific folder
    #root = 'D:\\Zz1\\*'          # all the subfolders too
    date_file_list = []
    for folder in glob.glob(root):
        print "folder =", folder
        # select the type of file, for instance *.jpg or all files *.*
        for file in glob.glob(folder + '/*.*'):
            # retrieves the stats for the current file as a tuple
            # (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)
            # the tuple element mtime at index 8 is the last-modified-date
            stats = os.stat(file)
            # create tuple (year yyyy, month(1-12), day(1-31), hour(0-23), minute(0-59), second(0-59),
            # weekday(0-6, 0 is monday), Julian day(1-366), daylight flag(-1,0 or 1)) from seconds since epoch
            # note:  this tuple can be sorted properly by date and time
            lastmod_date = time.localtime(stats[8])
            #print image_file, lastmod_date   # test
            # create list of tuples ready for sorting by date
            date_file_tuple = lastmod_date, file
            date_file_list.append(date_file_tuple)
    
    #print date_file_list  # test
    date_file_list.sort()
    date_file_list.reverse()  # newest mod date now first
    print "%-40s %s" % ("filename:", "last modified:")
    for file in date_file_list:
        # extract just the filename
        folder, file_name = os.path.split(file[1])
        # convert date tuple to MM/DD/YYYY HH:MM:SS format
        file_date = time.strftime("%m/%d/%y %H:%M:%S", file[0])
        print "%-40s %s" % (file_name, file_date)
    

    希望这会有所帮助

    谢谢

    【讨论】:

      猜你喜欢
      • 2018-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-11
      • 1970-01-01
      • 1970-01-01
      • 2022-01-14
      • 2020-03-16
      相关资源
      最近更新 更多