Skip to content

Instantly share code, notes, and snippets.

@arthuralvim
Created December 8, 2018 21:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arthuralvim/42ebb704b88dfb2a91b6371a444f5bfa to your computer and use it in GitHub Desktop.
Save arthuralvim/42ebb704b88dfb2a91b6371a444f5bfa to your computer and use it in GitHub Desktop.
Just a script to get some information about my files.
import os
import sys
import json
import datetime
from collections import namedtuple
from pathlib import Path
_timestamp_convert = datetime.datetime.fromtimestamp
def json_serial(obj):
if isinstance(obj, (datetime.datetime, datetime.date)):
return obj.isoformat()
raise TypeError ("Type %s not serializable" % type(obj))
class FileInfo(object):
def __init__(self, file_entry):
super(FileInfo, self).__init__()
self.file_entry = file_entry
def out(self):
print(self.file_entry)
print(self.info)
print(self.info_json)
@property
def info(self):
return {
'is_dir': self.file_entry.is_dir(),
'is_file': self.file_entry.is_file(),
'is_hidden': self.file_entry.name.startswith('.'),
'date_created': _timestamp_convert(self.file_entry.stat().st_ctime),
'date_last_access': _timestamp_convert(self.file_entry.stat().st_atime),
'date_last_modification': _timestamp_convert(self.file_entry.stat().st_mtime),
'size': self.file_entry.stat().st_size,
'ext': os.path.splitext(self.file_entry.path)[1],
'path': self.file_entry.name,
'full_path': self.file_entry.path,
}
@property
def info_json(self):
return json.dumps(self.info, indent=4, default=json_serial)
def get_tree_files_info(path):
files_info = []
for fi in os.scandir(path):
if fi.is_dir(follow_symlinks=False):
files_info.append(FileInfo(fi).info)
files_info.extend(get_tree_files_info(fi.path))
else:
files_info.append(FileInfo(fi).info)
return files_info
if __name__ == '__main__':
example_cmd = """
Example of usage:
$ files_info.py path/to/analyze data.json
"""
if len(sys.argv) < 3 :
print(example_cmd)
raise Exception('Problems with program usage.')
_, path, filename, *extra = sys.argv
if not Path(path).exists():
raise Exception('Path does not exists.')
files_info = get_tree_files_info(path)
with open(filename, 'w') as f:
json.dump(files_info, f, indent=4, default=json_serial)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment