Python: Make a class to read files in a directory
I am trying to teach myself how to make classes in Python. I am currently able to write a class that enables me to draw multiple shapes using the same class which is pretty basic.
I am having trouble with more advanced tasks using classes, for instance I would like to be able to make a class which includes functions such as how many files are in a particular directory.
I guess my question is How would I make a class that reads into a directory and tell me how many files are in the directory?
Thanks, sorry if it isnt clear
The function you are looking for is os.listdir.
Given a directory /tmp/foo with files named bar and baz:
>>> import os >>> os.listdir('/tmp/foo') ['baz', 'bar']
When you use os.listdir, you will also want to use os.path.isfile to test whether each entry you are dealing with is actually a file, since directory names are returned as well.
It seems a bit overkill to use a class, but here's a starting point:
import os class DirectoryLister(object): def __init__(self, *args): self.directory = os.listdir(*args) @property def count(self): return len(self.directory)
dl = DirectoryLister('/home/jon') print dl.directory print dl.count
You may also want to offer other argument to filter out non-files, or potentially look at glob to do wild card matching, etc...
os.listdir() returns a list of contents of a directory. If I understood the question correctly.
So a class would hold a function wrapper for that function, if you would like to make a new class for it. Not sure what you mean with "reads into a directory"
class YourClass: def __init__(self): #initialize here def countFilesInDir(self,directory): return len(os.listdir(directory))
or something like that