Skip to content

Instantly share code, notes, and snippets.

@will-hart
Last active October 30, 2018 03:08
Show Gist options
  • Save will-hart/aa96663390c8f34b4fb2568c137ec3cb to your computer and use it in GitHub Desktop.
Save will-hart/aa96663390c8f34b4fb2568c137ec3cb to your computer and use it in GitHub Desktop.
Get file information in a directory
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 30 13:43:22 2018
@author: Will Hart
"""
from datetime import datetime
from os import walk, path
# Edit these values to change behaviour
f = ["directory,file_name,creation_date,size_in_bytes,extension"]
start_path = "D:/MyFolder"
extensions = ['.jpg', '.png', '.tiff']
output_file = 'results.csv'
def walk_dir(dir_path, list_of_files):
for (dirpath, dirnames, filenames) in walk(dir_path):
for x in filenames:
full_path = path.join(dirpath, x)
_, ext = path.splitext(full_path)
if not ext in extensions:
continue
ctime = path.getctime(full_path) # windows only
ctime_formatted = datetime.fromtimestamp(ctime).strftime('%Y-%m-%d %H:%M:%S')
fsize = path.getsize(full_path)
list_of_files.append(f"{dirpath},{x},{ctime_formatted},{fsize},{ext.replace('.','')}")
for d in dirnames:
walk_dir(d, list_of_files)
if __name__ == '__main__':
walk_dir(start_path, f)
with open(output_file, 'w') as output:
output.write("\n".join(f))
print(f"Results written to {output_file}")
directory file_name creation_date size_in_bytes extension
D:/Drive/001/Data Page1.jpg 2018-07-09 15:44:25 1866378 jpg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment