As I start adding more code, I want to separate different functionality into different python files. In Python, you call these separate files modules. I need to learn how to use modules in Python.
The main script has got all the wxPython code. That probably needs to be separated out as well in due course. Using the SOLID principle, each class should have a single responsibility. I need to add the code to walk through the files, but this needs to be in a separate class, and a separate python file.
I’ve taken the code that walks through the files, and made a new class called FileWalker. It doesn’t have to be a class, but if you’re going to separate things out, a class seems to be the logical way to go. At this point I’m done with snake case. At first I thought it might be the ‘Python way’ but there is so much code out there in both, I’m going to move back to my happy place.
The watchout here, if you aren’t used to Python – the first parameter in a class method must be ‘self’, otherwise you will get some very strange error messages.
import os
class FileWalker:
def walkThroughFiles(self, inPath, extensions = (".jpg", ".jpeg")):
for (dirpath, dirnames, filenames) in os.walk(inPath):
for filename in filenames:
if filename.lower().endswith(extensions):
yield (filename, os.path.join(dirpath, filename))
This is all in a file called ‘traverseFiles.py’ in the same folder as all the other python scripts.
This post at Make Use Of explained very nicely how to use code that is sitting in another file, in another ‘module’.
from traverseFiles import FileWalker
...
def onCollectClicked(self, event):
fileWalker = FileWalker()
for fname in fileWalker.walkThroughFiles(self.photoFolder.GetValue()):
print(fname)
This is nice and tidy, and apart from the indents and colons, it’s starting to look more like other languages now.