user3251325
user3251325

Reputation: 3

How can I getsize different files in a listdir?

I seem to be only able to find the "getsize" of my entire directory, instead of the individual files in the directory <= 64 bytes. Any ideas or suggestions would be really appreciated, thank you!

Here is my script:

#argument is directory path

import os, sys 

myDir = sys.argv[1]
myFiles = os.listdir(myDir)

for eachOne in myFiles:
    size = os.path.getsize(myFiles)
    if size <= "64":
       print "{0} is {1} bytes.".format(eachOne, size)

The goal is to print out the file name is XX bytes.

Upvotes: 0

Views: 359

Answers (1)

user2555451
user2555451

Reputation:

There are three problems here:

  1. You need to give os.path.getsize eachOne instead of myFiles.

  2. os.path.getsize returns an integer. Meaning, you need to compare size with another integer, not a string.

  3. You need to use os.path.join to give os.path.getsize the full path to the file. Otherwise, Python will not know where the file is.

Below is a version of your script with these problems addressed:

import os, sys 

myDir = sys.argv[1]
myFiles = os.listdir(myDir)

for eachOne in myFiles:
    size = os.path.getsize(os.path.join(myDir, eachOne))
    if size <= 64:
       print "{0} is {1} bytes.".format(eachOne, size)

Upvotes: 1

Related Questions