Skip to content

Instantly share code, notes, and snippets.

@kionay
Created October 14, 2018 02:56
Show Gist options
  • Save kionay/5fd1fd699b2ec5471d52d1064c0830c1 to your computer and use it in GitHub Desktop.
Save kionay/5fd1fd699b2ec5471d52d1064c0830c1 to your computer and use it in GitHub Desktop.
Changes the Creation Date attribute of files at the top of a given Drive in windows so that Create Date orders the same as Alphabetically
# pylint: disable=I1101,E1101
"""
os for generic filesystem operations
argparse to accept a drive letter
time as a basis for creation time
pywintypes and win32file for windows file manipulation
"""
import os
import argparse
import time
import pywintypes
import win32file
def get_args():
"""Sets up command-line arguments. Returns the parsed arguments."""
parser = argparse.ArgumentParser()
parser.add_argument("driveletter",
type=str,
help="The drive letter assigned to the device mounted in windows.")
args = parser.parse_args()
return args
def files(path):
""" Returns a list of filenames from the given directory.
https://stackoverflow.com/questions/14176166/list-only-files-in-a-directory
"""
for file in os.listdir(path):
if os.path.isfile(os.path.join(path, file)):
yield file
# https://stackoverflow.com/questions/4996405/how-do-i-change-the-file-creation-date-of-a-windows-file-from-python
def change_file_create_time(path, ctime):
"""modifies a given file's Creation Date attribute using a given unix timestamp"""
# path: your file path
# ctime: Unix timestamp
# open file and get the handle of file
# API: http://timgolden.me.uk/pywin32-docs/win32file__CreateFile_meth.html
handle = win32file.CreateFile(
path, # file path
win32file.GENERIC_WRITE, # must opened with GENERIC_WRITE access
0,
None,
win32file.OPEN_EXISTING,
0,
0
)
# create a PyTime object
# API: http://timgolden.me.uk/pywin32-docs/pywintypes__Time_meth.html
py_time = pywintypes.Time(ctime)
# reset the create time of file
# API: http://timgolden.me.uk/pywin32-docs/win32file__SetFileTime_meth.html
win32file.SetFileTime(
handle,
py_time
)
def main():
"""The primary or controlling function.
"""
args = get_args()
if len(args.driveletter) != 1:
print("Only the drive letter is allowed.")
exit()
abspath = os.path.abspath(args.driveletter + ":")
files_in_drive = sorted(list(files(abspath)),
key=lambda filename: [x for x in filename if x.isalnum()])
current_time = int(time.time())
for index, media in enumerate(files_in_drive):
full_path = os.path.join(abspath, media)
print(media)
change_file_create_time(full_path, current_time + index)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment