Skip to content

Instantly share code, notes, and snippets.

@CypherpunkSamurai
Last active March 18, 2022 18:55
Show Gist options
  • Select an option

  • Save CypherpunkSamurai/17d322e6a4222f7a0e2ff0ecca30dd6d to your computer and use it in GitHub Desktop.

Select an option

Save CypherpunkSamurai/17d322e6a4222f7a0e2ff0ecca30dd6d to your computer and use it in GitHub Desktop.
Get the oldest file from a directory with python3

Get the oldest file from a directory with python3

This example is taken from stackoverflow.

Solution 1

list_of_files = os.listdir('log')    

if len(list_of_files) >= 25:
    oldest_file = min(list_of_files, key=os.path.getctime)
    os.remove(os.path.abspath(oldest_file))

Solution 2 (without using abspath)

list_of_files = os.listdir('log')
full_path = ["log/{0}".format(x) for x in list_of_files]

if len(list_of_files) == 25:
    oldest_file = min(full_path, key=os.path.getctime)
    os.remove(oldest_file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment