我有四个文件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)
但资源管理器中的文件仍按名称排序。有线索吗?