user3595632
user3595632

Reputation: 5730

Why os.path.getsize() throw error in python?

I'm trying to print the size of all file lists, but it throws error. Here is the code :

import os

def printSize(fileAbsPath) :
  print os.path.getsize(fileAbsPath)


for folderName, subfolders, filenames in os.walk('/Users/kris/Desktop'):
  for filename in filenames :
    try :
      printSize(os.path.abspath(filename))
    except Exception as err:
      print 'An exception happend : ' + str(err)

And, the errors are :

An exception happend : [Errno 2] No such file or directory: '/Users/kris/Desktop/AutomateBoringStuff/.DS_Store'
An exception happend : [Errno 2] No such file or directory: '/Users/kris/Desktop/AutomateBoringStuff/.gitignore'
An exception happend : [Errno 2] No such file or directory: '/Users/kris/Desktop/AutomateBoringStuff/.gitmodules'
An exception happend : [Errno 2] No such file or directory: '/Users/kris/Desktop/AutomateBoringStuff/.localized'
.
.
.
.
An exception happend : [Errno 2] No such file or directory: '/Users/kris/Desktop/AutomateBoringStuff/BLE Scanner.m4a'
An exception happend : [Errno 2] No such file or directory: '/Users/kris/Desktop/AutomateBoringStuff/Screen Shot 2015-07-23 at 3.30.52 PM.png'

I don't know what's wrong with it. I thought it is kinda related with 'concealed files' but it wasn't.

Upvotes: 2

Views: 4591

Answers (3)

Ehsan
Ehsan

Reputation: 4474

According to docs.python os.path.getsize(path) Return the size, in bytes, of path.

Raise os.error if the file does not exist or is inaccessible

So catch this exception or make sure the file exists.

Upvotes: 0

David Ehrmann
David Ehrmann

Reputation: 7576

From the docs of os.walk (emphasis added):

Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames). dirpath is a string, the path to the directory. dirnames is a list of the names of the subdirectories in dirpath (excluding '.' and '..'). filenames is a list of the names of the non-directory files in dirpath. Note that the names in the lists contain no path components. To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name).

I'm guessing you ran your script in AutomateBoringStuff (so it's the working directory), but the files are actually in Desktop.

/Users/kris/Desktop/AutomateBoringStuff/BLE Scanner.m4a should be /Users/kris/Desktop/BLE Scanner.m4a

Upvotes: 0

Robᵩ
Robᵩ

Reputation: 168876

Try this:

  printSize(os.path.abspath(os.path.join(folderName, filename)))

Upvotes: 3

Related Questions