【问题标题】:sort my file paths according to their date of creation?根据创建日期对我的文件路径进行排序?
【发布时间】:2020-09-08 09:39:36
【问题描述】:

我写了一个在 tkinter 中显示我的函数,用每个最后修改日期标记目录中的所有文件。

我希望这些文件在我的标签中按升序排序,我尝试使用 sorted() 方法,但它不起作用。

有我的功能:

def CheckModifyTime():

    path = "C:\\Users\\sohei\\Desktop\\Perso\\TestScriptWinSCP"
    myDir = os.listdir(path)
    window = tk.Toplevel(GuiInterface)
    window.geometry("800x800")
    today = date.today()
    for root, dirs , files in os.walk(path):
        for f in files:
            myFiles = os.path.join(root, f)
            modifyTime = myFiles + " " + time.ctime(os.path.getmtime(myFiles))
            
            #print(modifyTime)
            myVar = StringVar()
            myVar.set(modifyTime)
            label = tk.Entry(window , textvariable = myVar , width = "100").pack()

并使用sorted() 方法:

def CheckModifyTime():

    path = "C:\\Users\\sohei\\Desktop\\Perso\\TestScriptWinSCP"
    myDir = os.listdir(path)
    window = tk.Toplevel(GuiInterface)
    window.geometry("800x800")
    today = date.today()
    for root, dirs , files in os.walk(path):
        for f in files:
            
            myFiles = os.path.join(root, f)
            modifyTime = myFiles + " " + time.ctime(os.path.getmtime(myFiles))
            
            #print(modifyTime)
            myVar = StringVar()
            
            sortedFiles = sorted(modifyTime , key=lambda t: os.stat(t).st_mtime)
            myVar.set(sortedFiles)
            print(sortedFiles)
            label = tk.Entry(window , textvariable = myVar , width = "100").pack()

您有想法对我的文件进行排序吗?

【问题讨论】:

  • 除非我在这里遗漏了什么,否则您会尝试在每次迭代中“排序”单个对象。为什么“myFiles”是复数形式?这是一条路。这是一回事。检查你的变量名,然后可能会更有意义。
  • @Neil 是的,我解决了我的问题,真的很容易,但我已经在我的代码上待了 5 个小时,因为我没有注意到这很容易,谢谢

标签: python file tkinter


【解决方案1】:

我会为他们制作一个对象。

class DatedFile:
    def __init__(self, name, date):
        self.name = name
        self.date = date
    def __lt__(self, other):
        return self.date<self.other

lt 方法是一个内置的“魔术”函数,每当使用“小于”运算符时都会调用该函数。这一点很重要,因为 sort 和 sorted 函数实际上只是运行了很多 a

然后将所有带日期的文件放入由此类实例组成的列表中。

my_files = []
for f in files:
    my_files.append(DatedFile(name, date))
my_files.sort()

然后它将按日期对它们进行排序,您可以像访问任何其他类(.name 和 .date)一样访问它们的变量

让我知道这是否有帮助,或者如果您有任何需要更多示例的问题!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-22
    • 1970-01-01
    • 1970-01-01
    • 2018-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多