forked from rcarmo/python-utils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfilekit.py
78 lines (66 loc) · 2.33 KB
/
filekit.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright (c) 2012, Rui Carmo
Description: File utility functions
License: MIT (see LICENSE.md for details)
"""
import os
import sys
import logging
import zipfile
log = logging.getLogger()
def path_for(name, script=__file__):
"""Build absolute paths to resources based on app path"""
if 'uwsgi' in sys.argv:
return os.path.join(os.path.abspath(os.path.join(os.path.dirname(script),'..')),name)
return os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]),name))
def locate(pattern, root=os.getcwd()):
"""Generator for iterating inside a file tree"""
for path, dirs, files in os.walk(root):
for filename in [os.path.abspath(os.path.join(path, filename)) for filename in files if fnmatch.fnmatch(filename, pattern)]:
yield filename
def walk(top, topdown=True, onerror=None, followlinks=False, ziparchive=None, zipdepth=0):
"""Reimplementation of os.walk to traverse ZIP files as well"""
try:
if (os.path.splitext(top)[1]).lower() == '.zip':
if ziparchive:
# skip nested ZIPs.
yield top, [], []
else:
ziparchive = zipfile.ZipFile(top)
names = list(set(map(lambda x: [p+'/' for p in x.split('/') if p != ""][zipdepth],ziparchive.namelist())))
else:
names = os.listdir(top)
except error, err:
if onerror is not None:
onerror(err)
return
dirs, nondirs = [], []
if ziparchive:
for name in names:
if name == '__MACOSX/':
continue
if name[-1::] == '/':
dirs.append(name)
else:
nondirs.append(name)
else:
for name in names:
if os.path.isdir(os.path.join(top, name)):
dirs.append(name)
else:
nondirs.append(name)
if topdown:
yield top, dirs, nondirs
for name in dirs:
new_path = os.path.join(top, name)
if ziparchive:
for x in walk(new_path, topdown, onerror, followlinks):
yield x
else:
if followlinks or not islink(new_path):
for x in walk(new_path, topdown, onerror, followlinks):
yield x
if not topdown:
yield top, dirs, nondirs