Function for examine content of directory

Ian Foote ian at feete.org
Thu Sep 6 11:06:35 EDT 2012


On 06/09/12 15:56, Tigerstyle wrote:
> Hi guys,
>
> I'm trying to write a module containing a function to examine the contents of the current working directory and print out a count of how many files have each extension (".txt", ".doc", etc.)
>   
> This is the code so far:
> --
> import os
>
> path = "v:\\workspace\\Python2_Homework03\\src\\"
> dirs = os.listdir( path )
> filenames = {"this.txt", "that.txt", "the_other.txt","this.doc","that.doc","this.pdf","first.txt","that.pdf"}
> extensions = []
Try using a set here instead of a list:
     extensions = set()
> for filename in filenames:
>      f = open(filename, "w")
>      f.write("Some text\n")
>      f.close()
>      name , ext = os.path.splitext(f.name)
>      extensions.append(ext)
and use:
         extensions.add(ext)

This should take care of duplicates for you.

Regards,
Ian



More information about the Python-list mailing list