Skip to content

Instantly share code, notes, and snippets.

@Ivlyth
Last active March 28, 2016 08:08
Show Gist options
  • Save Ivlyth/9f19abe7e8affada63a4 to your computer and use it in GitHub Desktop.
Save Ivlyth/9f19abe7e8affada63a4 to your computer and use it in GitHub Desktop.
always get file path relative to my current file path
-- ~/root
    |--module1
        |--sub_dir1
              |--source.0.ext
        |--source.1.ext
        |--m1.py
    |--module2
        |--source.2.ext
        |--m2.py
# in m1.py
f = FileFinder() # means directory `~/root/module1`
f = f.child('sub_dir1') # means directory `~/root/module1/sub_dir1`
f.file('source.0.ext') # return `~/root/module1/sub_dir1/source.0.ext`
# so , we can get the `source.0.ext` path in one statement:
FileFinder().child('sub_dir1').file('source.0.ext')

# in m2.py
# to get source.0.ext's path
FileFinder().parent.child('module1').child('sub_dir1').file('source.0.ext')

now we can always get file path relative to my current file path :)

import inspect
import os
class FileFinder(object):
def __init__(self, current_directory=u'.'):
if current_directory == u'.' or current_directory == u'':
frame = inspect.currentframe()
frame = frame.f_back
fi = inspect.getframeinfo(frame)
self._current_directory = os.path.dirname(fi.filename)
else:
_c = os.path.expanduser(current_directory)
if not os.path.isdir(_c) and os.path.isabs(_c):
raise Exception(u'`current_directory` must be a absolute directory path')
self._current_directory = _c
@property
def path(self):
return self._current_directory
@property
def parent(self):
_p = os.path.dirname(self._current_directory)
if _p == self._current_directory:
raise Exception(u'no more parent directory for %s' % self._current_directory)
return FileFinder(_p)
def child(self, directory_name):
fs = os.listdir(self._current_directory)
for fname in fs:
if directory_name == fname:
_d = os.path.join(self._current_directory, directory_name)
if os.path.isdir(_d):
return FileFinder(_d)
raise Exception(u'%s in %s is not a directory'%(directory_name, self._current_directory))
else:
raise Exception(u'no such directory in directory %s: %s' % (self._current_directory, directory_name))
def file(self, file_name):
fs = os.listdir(self._current_directory)
for fname in fs:
if file_name == fname:
return os.path.join(self._current_directory, file_name)
else:
raise Exception(u'no such file in directory %s: %s' % (self._current_directory, file_name))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment