python Instance code for arranging files in order of modification time

  • 2021-07-26 08:29:52
  • OfStack

python arranges the files in order of modification time, and the specific code is as follows:


import os
def sort_file_by_time(file_path):
  files = os.listdir(file_path)
  if not files:
    return
  else:
    files = sorted(files, key=lambda x: os.path.getmtime(os.path.join(file_path, x)))# Format interpretation : Right files Sort .x Yes files Elements of ,: The following is the basis for sorting .  x Just the filename , So take it with you join.
    return files
print(sort_file_by_time("."))

The content represented by the lambda function in sorted is the basis for sorting (key)

It is found that list. sort () returns None, while sorted (list) can return an ordered list.

ps: python Find all files in the specified folder and arrange them in reverse order by modification time

The code is as follows:


import os, glob, time
def search_all_files_return_by_time_reversed(path, reverse=True):
  return sorted(glob.glob(os.path.join(path, '*')), key=lambda x: time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(os.path.getctime(x))), reverse=reverse)

Summarize


Related articles: