-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathFileNavigator.py
More file actions
65 lines (55 loc) · 2 KB
/
Copy pathFileNavigator.py
File metadata and controls
65 lines (55 loc) · 2 KB
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
import sys
import os
import re
try:
import win32api
except ImportError:
print("Error: Expected Windows-based Filesystem")
sys.exit(1)
DRIVES = "D:\\","R:\\","C:\\"
class FileNavigator(object):
def __init__(self,drives):
#get all accessible drive letters
self._drives = win32api.GetLogicalDriveStrings().split('\000')[:-1]
self._drive = None
for drive in drives:
if drive in self._drives:
self._drive = drive
break
if self._drive is None:
self._drive = self._drives[0]
def findLatest(self,matches='.*',path=None,max_depth=2):
"""Call recursive file finder and return result with latest mtime"""
self.matching_files = []
if path is None:
path = self._drive
self._find_latest(matches,path,max_depth,1)
return max(self.matching_files,key=os.path.getmtime)
def setDrive(self,drive):
if drive in self._drives:
self._drive = drive
else:
raise IOError("Unknown drive: {}".format(drive))
def _find_latest(self,matches='.*',path=None,max_depth=2,curr_depth=1):
"""Recursively search for files in drive self._drive up to recursion
depth max_depth
"""
files = []
try:
for f in os.listdir(path):
full_path = os.path.join(path,f)
os.path.getmtime(full_path)
files.append(full_path)
except PermissionError:
pass
#we need to look in all directories since we don't know if the latest
#matching file is in the latest updated path
for f in files:
if os.path.isdir(f) and curr_depth < max_depth:
self._find_latest(matches,f,max_depth,curr_depth+1)
else:
if re.match(matches,f):
self.matching_files.append(f)
if __name__=='__main__':
f = FileNavigator(DRIVES)
print(f.findLatest('.*VNIR.*hyspex$'))