代码之家  ›  专栏  ›  技术社区  ›  sync11

在目录中按大小对文件排序[已关闭]

  •  -3
  • sync11  · 技术社区  · 2 年前

    我有四个文件a.jpg(5kb),b.jpg(1Kb),c.jpg(3Kb)。目前,它们显示在按名称排序的目录中(Windows文件资源管理器:按->名称排序)。我想使用Python根据它们的大小对它们进行排序,并在文件资源管理器中反映变化,而不仅仅是在脚本中。 我使用ChatGPT得出:

    import os
    
    def sort_files_by_size(directory):
        # Get a list of files in the directory
        files = os.listdir(directory)
    
        # Create a list of tuples where each tuple contains the filename and its size
        file_sizes = [(file, os.path.getsize(os.path.join(directory, file))) for file in files]
    
        # Sort the list of tuples based on the second element (file size)
        sorted_files = sorted(file_sizes, key=lambda x: x[1])
    
        # Display the sorted files
        for file, size in sorted_files:
            print(f"{file}: {size} bytes")
    
        # Optionally, you can move or rename the files based on the sorted order
        for index, (file, _) in enumerate(sorted_files, start=1):
            new_name = f"{file}"
            os.rename(os.path.join(directory, file), os.path.join(directory, new_name))
    
    # Replace 'your_directory_path' with the actual path to your directory
    directory_path = 'images'
    sort_files_by_size(directory_path)
    

    但资源管理器中的文件仍按名称排序。有线索吗?

    1 回复  |  直到 2 年前
        1
  •  1
  •   mighty_mike    2 年前

    正如您正确地注意到的,当您打开该目录时,文件资源管理器使用它自己的排序逻辑。所以你不能随心所欲地推翻它。嗯,至少不容易。

    我可以提供2个技巧:

    1. 使用您的ChatGPT代码,并对其进行修改以将文件重命名为 01最大,02次大等。。。

    2. 或者放弃Python脚本,配置文件资源管理器。检查这个 How to set default sorting logic