Skip to content

Instantly share code, notes, and snippets.

Created Mar 30, 2021
What would you like to do?
iterate over list of files & write information about them (including MIME type) to CSV
#!/usr/bin/env python3
import csv
import os
import subprocess
with open('files.csv', 'w') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['path', 'size (bytes)', 'time last accessed', 'time last modified', 'time created', 'mime type'])
with open('dbcheck-files.txt', 'r') as listfile:
for path in listfile:
path = path.strip()
stat = os.stat(path)
# python's mimetypes library only guesses based on file extension, not contents
# so seems like UNIX `file` command is much more informative
result =['file', path], stdout=subprocess.PIPE, universal_newlines=True)
mime = ''.join(result.stdout.split(': ')[1:])
writer.writerow([path, stat.st_size, stat.st_atime, stat.st_mtime, stat.st_ctime, mime])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment