Get sorted file names from a directory by creation date in Python
In this article, we will understand how to retrieve sorted file names from a directory using Python. For this, we would make use of the Python glob library’s glob function. There is no need to install this module externally because it is already included with Python.
Firstly, The glob function would be used to obtain the list of files/directories within the specified directory, then we will filter the previous output with the os.path.isfile command which assures that only files are present in the list, not directories/folders.
Syntax of methods used:
In Python, the glob module is used to retrieve files/pathnames matching a specified pattern.
Syntax: glob(pathname, *, recursive=False):
Return: It returns list of path names that match pathname given, which must be a string containing a path specification. List can be empty too.
The os.path.isfile() method in Python is used to check whether the specified path is an existing regular file or not.
Return: This method returns a Boolean value of class bool. This method returns True if specified path is an existing regular file, otherwise returns False.
The os.path.getctime flag would be used to find the creation timestamps of these files, which would be used to sort them based on their creation time.
Return: This method returns a floating-point value of class ‘float’ that represents the ctime (in seconds) for the specified path.
The path in which the files exist: C:\Users\apples\images
The following program would give the below file list in the same order. If the above directory is sorted in ascending order based on the timestamp of creation, it would look as follows:
Firstly the variable named path is used to store the path of the directory on which we want to perform our operations. Then the list of files and folders inside the path was obtained (using the * “asterisk” wildcard) and was filtered to remove the directories from the list (using the filter function). The result of the filter function is converted to list data structure. Then the list data structure is sorted based on the creation time constraint, which sorts the elements (filenames) in the list based on the time they were created in ascending order. In the end, the list is displayed.
‘C:\\Users\\apples\\images\\yes dad i a mwinning.png’, ‘C:\\Users\\apples\\images\\ss.png’,
‘C:\\Users\\apples\\images\\unnamed.jpg’, ‘C:\\Users\\apples\\images\\Screenshot 2020-12-15 161254.png’,
‘C:\\Users\\apples\\images\\Screenshot 2020-12-16 123348.png’, ‘C:\\Users\\apples\\images\\sample_text.png’,
‘C:\\Users\\apples\\images\\made at aposter at my house.ai’, ‘C:\\Users\\apples\\images\\PRDR3769186715_1’,
- If the last print statement is replaced by print(“\n”.join(files)) the output would appear vertically than horizontally (better for visualizing the effect produced).
- glob.glob doesn’t work with filenames containing a period as the first character
Please Login to comment...