Reputation: 27
I have a directory tree structure as follows:
C:\Users\Win-8.1\Desktop\gangotri\images\smb\1998\05_06_1998\LT51460391998156XXX02.tar\LT51460391998156XXX02\ReflectanceB3.tif
Firstly, I want to come to the following depth (=6):
C:\Users\Win-8.1\Desktop\gangotri\images\smb
which contains two folders.
Secondly, I want to "recursively" come to the following depth (=7):
C:\Users\Win-8.1\Desktop\gangotri\images\smb\1998
which has folders containing data of particular years.
Thirdly, I want to come to the following depth (=11):
C:\Users\Win-8.1\Desktop\gangotri\images\smb\1998\05_06_1998\LT51460391998156XXX02.tar\LT51460391998156XXX02\ReflectanceB3.tif
which has a lot of files. However, I want to locate precisely two, each with a particular name (=ReflectanceB3.tif, =ReflectanceB4.tif) and multiply a constant to each one of them.
Lastly, I want to come back to depth (=6), enter the other folder and start the second and third process again.
Upvotes: 0
Views: 114
Reputation: 177
You can use Python's glob module. This, as the name suggests, works with globs.
I'm not sure about the 'depth=7' part, but please find the rest of the answer below.
To access any file at depth 11, inside C:\Users\Win-8.1\Desktop\gangotri\images\smb, the glob expression will be
'C:\\Users\\Win-8.1\\Desktop\\gangotri\\images\\smb\\*\\*\\*\\*\\*'
.
Note that you need to escape the backslash (windows directory seperator) by adding another backslash.
If you want to only access ReflectanceB3.tif and ReflectanceB4.tif, your expression becomes 'C:\\Users\\Win-8.1\\Desktop\\gangotri\\images\\smb\\*\\*\\*\\*\\ReflectanceB[34].tif'
If, for instance, you want to match only 4 digit numeric directories after smb (feeble attempt at matching years), you could use 'C:\\Users\\Win-8.1\\Desktop\\gangotri\\images\\smb\\[0-9][0-9][0-9][0-9]\\*\\*\\*\\ReflectanceB[34].tif'
Glob expressions can solve needs similar to that of yours. However, it has limitations, as seen by trying to choose only directories which are years. For this, one needs to use the extremely powerful Regular Expressions module. There does not appear to be an 'out of the box' module in python which combines directory traversal with regex pattern matching - you'll need to do the traversal yourself.
Upvotes: 1