Skip to content

Instantly share code, notes, and snippets.

@aalokt89
Last active February 12, 2023 08:03
Show Gist options
  • Save aalokt89/c8736420d918d68bf81fc545304e835e to your computer and use it in GitHub Desktop.
Save aalokt89/c8736420d918d68bf81fc545304e835e to your computer and use it in GitHub Desktop.
import os
import datetime
import json
# convert time to human readable format
def convertDate(timestamp):
d = datetime.datetime.utcfromtimestamp(timestamp)
formatedDate = d.strftime('%b %d, %Y')
return formatedDate
def getDirDetails(path=os.getcwd()):
fileList = []
pathExists = os.path.exists(path)
isFile = os.path.isfile(path)
isDir = os.path.isdir(path)
if pathExists and isDir:
for root, dirs, files in os.walk(path):
for file in files:
# get file path
filePath = os.path.join(root, file)
# get file size
fileSize = round(os.path.getsize(filePath) / 1024, 1)
# get and convert creation date
fileCreationDate = convertDate(os.path.getctime(filePath))
# add file details into a dict
fileDict = {
'file_name': file,
'path': filePath,
'size_kb': fileSize,
"date_created": fileCreationDate
}
# add file dicts into the list
fileList.append(fileDict)
# json of file
pathFilesJSON = json.dumps(fileList, indent=4)
return pathFilesJSON
elif pathExists and isFile:
print(f"Error: The path '{path}' must be a directory.")
elif pathExists == False:
print(f"Error: The path '{path}' does not exist.")
#call the function and print the results
print(getDirDetails("YOUR_PATH"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment