Reputation: 77
I'm trying to iterate through some directories I have to return the total size of the folder. However, I get this error
OSError: [Errno 2] No such file or directory:
for one of the files in one of the subdirectories in my folder after running the function in the code. Why does this error occur, even though my function is iterating through a folder, so the file must exist?
def get_size(folder):
folder_size = 0
for (path, dirs, files) in os.walk(folder):
for file in files:
filename = os.path.join(path, file)
folder_size += os.path.getsize(filename)
return folder_size
Upvotes: 2
Views: 2736
Reputation: 363395
A likely cause of this error during a walk is encountering a "dangling" symbolic link, i.e. the link target does not exist.
To work around this issue, decide what you want to do with dangling links:
os.path.islink
to check if a file is a link. lstat
instead of stat
, this gives the size of a link as the length of the target, rather than trying to resolve the link. You should replace the os.path.getsize(filename)
with os.lstat(filename).st_size
. Upvotes: 3