Change Contents of the Bubble
Welcome to CS1315. Click on the python to add comments.

Looking for the book? They have it at the Engineer's Bookstore at 748 Marietta St NW. Here is there website: http://www.engrbookstore.com/ - Monica

Hotspots: Slides and CodeTA CornerComments?AnnouncementsFAQStatic Webspace
View this PageEdit this PageUploads to this PageHistory of this PageHomeRecent ChangesSearchHelp Guide

Fall 2006 Midterm 2 Review: Modules

import os
def media():
 count=0
 for file in os.listdir():
   file.lower()
      if file.endswith(".jpg"):
         count=count+1
      if file.endswith(".wav"):
         count=count+1
 return count


Stacy Schwaiger

You need to take in directory as a parameter and then search for the files in that directory. Also, your 'if' conditions should check whether the extensions are capitalized or not. -Bobby Mathew
It looks to me like your taking care of capitalization with file.lower(), but do you need to indent your if statements after file.lower()? Amanda Bennett

why do you need to include count = 0?
The question is asking you to count the number of files. You need a seperate variable to keep track of it since there's no easier way of doing it. So, we're making a variable called count. We're giving it the value 0 so that it starts counting correctly. If you don't put that statement at all, it will give you an error saying that the variable is not defined or something. -Bobby Mathew

what is os?
os is a module in JES - stands for Operating System. It contains a list of functions which deal with the files/folders on your computer. The only function you need to know is os.listdir(directory) -Bobby Mathew


import os
def media(dir):
  count=0
  for file in os.listdir(dir):
    file.lower()
    if file.endswith(".jpg"):
      count=count+1
    if file.endswith(".wav"):
      count=count+1
  return count

Why do I get the error "An error occurred while making an operating system call."?
It works fine on my computer. Make sure you used pickAFolder() to input your directory or have a right path to the folder. - Bobby Mathew

what is the file.lower mean?
It changes the entire filename to lowercase letters. Its being done here so that you don't have to search for uppercase extensions like how the question asks. You can also use 2 more 'if' conditions and avoid doing file.lower. - Bobby Mathew
BTW, there is a small mistake still in the code above. file.lower() returns a value that is equal to the string "file" turned into lower case. It does not change the string "file" into lower case. That string stays the same. So the line should really be something like
   name = file.lower()
   if name.endswith(".jpg"):
   .......

Colin Potts



Link to this Page