Hopefully this question is easier than I think it is. :)

I have a directory with thousands and thousands of flv and jpeg files in it. I want to loop through the directory, get the file names and their sizes (in bytes) I've tried searching the web for a function to get the sizes, but I can't seem to find anything that talks about handling anything other than txt files. Any help would be much appreciated.

Recommended Answers

All 2 Replies

Hi zachabesh,

Can't you just use os.path.getsize()? You call it with the name of the file as an argument.

Awesome! Thank you so much! I guess I didn't believe it would be that simple.

Heres what I did, which accomplished the task, but took forever as you might imagine.

import os
import dircache

#get the files
files = dircache.listdir("directory")

write = open("text.txt","w")
print "Onto the loop...."
print "-----------------"
c = 0

for x in files:
    
file = open(x, "rb")
    filelines = file.read()
    w = len(filelines)/1000
    file.close()
    j = "%s, %s\n" %(x,w)
    j = str(j)
    print "%d) %s" %(c,j)
    write.write(j)
    c = c + 1
print "Done!"
write.close()
print "File closed!"

after simplifying:

import os
import dircache

#Get the files from the directory
files = dircache.listdir("directory")

#open a file to write the files and the sizes into
write = open("text.txt","w")

print "Onto the loop...."
print "-----------------"

c = 0
for x in files:
    
    #open the file, get size
    file = open(x, "rb")
    w = os.path.getsize(file)
    file.close()
    #file closed
    
    j = "%s, %s\n" %(x,w)
    j = str(j)
    print "%d) %s" %(c,j)
    write.write(j)
    c = c + 1
    
print "Done!"
write.close()
print "File closed!"

Much faster!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.