Summer 2006- Questions on import os
Questions?
When I try to count 40 ".jpg" instances, I get an output of 40 1's rather than just "40". What am I doing wrong?
import os
def titleDirectory(dir):
for file in os.listdir(dir):
if file.endswith(".jpg"):
print file.count(file)
NOTE-ignore the tab errors
I think its doing that because its inside the loop and its printing out the number of jpg files if that condition is true. What you might want to do, instead of file.count(file), just do
def titleDirectory(dir):
count = 0
for file in os.listdir(dir):
if file.endswith(".jpg") or file.endswith(".JPG"):
count = count + 1
print count
- Bobby Mathew |
This is how we did it in recitation and it seemd to work:
import os
def media(dir):
pic=" .gif .jpg .png .bmp"
text=" .txt .rtf .doc"
files=os.listdir(dir)
pics=0
texts=0
pys=0
for file in files:
extension=file[file.rfind('.'):]+' '
if pic.find(extension)!=-1:
pics=pics+1
if text.find(extension)!=-1:
texts=texts+1
if extension=='.py':
pys=pys+1
print "pictures:",pics
print "text:",texts
print "pys:",pys
Oops, forgot my tags.
Link to this Page