Skip to content

Instantly share code, notes, and snippets.

@psobot
Created April 3, 2018 13:26
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 psobot/feec2d84f9b01e97c493218e40fa993b to your computer and use it in GitHub Desktop.
Save psobot/feec2d84f9b01e97c493218e40fa993b to your computer and use it in GitHub Desktop.
Python File and Directory Helpers
import os
from glob import glob
class Directory(object):
def __init__(self, _dir=None):
if _dir:
self._dir = os.path.abspath(os.path.expanduser(_dir))
else:
self._dir = os.path.abspath(os.getcwd())
def __str__(self):
return self._dir
def __repr__(self):
return "<Directory %s>" % str(self)
@property
def parent(self):
return Directory(os.path.dirname(self._dir))
@property
def exists(self):
return os.path.isfile(str(self))
@property
def files(self):
for entry in os.listdir(str(self)):
if os.path.isfile(entry):
yield File(entry)
def files_matching(self, pattern):
for entry in glob(os.path.join(str(self), pattern)):
if os.path.isfile(entry):
yield File(entry)
@property
def directories(self):
for entry in os.listdir(str(self)):
if os.path.isdir(entry):
yield Directory(entry)
def file(self, file):
return File(self, file)
def dir(self, _dir):
return Directory(os.path.join(self._dir, _dir))
class File(object):
def __init__(self, _dir_or_path, filename=None):
if isinstance(_dir_or_path, Directory) and filename:
self._dir = _dir_or_path
self.filename = filename
else:
self._dir = Directory(os.path.dirname(_dir_or_path))
self.filename = os.path.basename(_dir_or_path)
def __str__(self):
return os.path.join(str(self._dir), self.filename)
def __repr__(self):
return "<File %s>" % str(self)
@property
def dir(self):
return self._dir
@property
def exists(self):
return os.path.isfile(str(self))
@property
def size(self):
return os.stat(str(self)).st_size
@property
def access_time(self):
return os.stat(str(self)).st_atime
@property
def modification_time(self):
return os.stat(str(self)).st_mtime
@property
def creation_time(self):
return os.stat(str(self)).st_ctime
def with_extension(self, ext):
fileparts = self.filename.split('.')
if len(fileparts) > 1:
fileparts = fileparts[:-1]
return File(self._dir, '.'.join(fileparts + [ext]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment