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

Answers


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)

Used like:

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


Need Your Help

how to send common request for the multiple tabs?

java javascript jquery ajax servlets

I am developing one timer in web application. in this timer i am sending update request at every 2 minutes to update the time in server. now problem is that when multiple tabs are open in browser w...

Union hack for endian testing and byte swapping

c++ c unions

For a union, writing to one member and reading from other member (except for char array) is UB.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.