I have created the following python script to list all files and their sizes present in directoris/sub-directories
Code A
files = glob.glob("%s/*.*"%os.getcwd())
sorted_file = sorted(files, key=os.path.getsize)
for path, dirs, files in os.walk(os.getcwd()):
for d in dirs:
for f in glob.iglob(os.path.join(path, d, '*.*')):
print f ,os.path.getsize(f)
I am getting the following error when it runs trhough the directories:
Traceback (most recent call last):
File "Test.py", line 27, in <module>
print f ,os.path.getsize(f)
File "/usr/lib/python2.6/genericpath.py", line 49, in getsize
return os.stat(filename).st_size
OSError: [Errno 2] No such file or directory: '/My/Folder/Perlx.x'
Strangely when I go to the /My/Folder/
in unix box and do a ls -l
, I can see Perlx.x
whihc it truns out is a Symbolic Link
Code B
for path, subdirs, files in os.walk(os.getcwd()):
for name in files:
f = os.path.join(path, name)
print f,os.path.getsize(f)
Error :
/My/Folder/BEA
Traceback (most recent call last):
File "Test.py", line 19, in <module>
print f,os.path.getsize(f)
File "/usr/lib/python2.6/genericpath.py", line 49, in getsize
return os.stat(filename).st_size
OSError: [Errno 2] No such file or directory: '/My/Folder/BEA'
In both cases BEA and Perlx.x are Symbolic Links
which exits in the specified folder. How do I get rid of this error?
To get rid of the error , I put in an extra condition which checks if the file is link or not.
for path, subdirs, files in os.walk(choicedir):
for name in files:
f = os.path.join(path, name)
if not os.path.islink(f):
modified = os.path.getmtime(f)
size = float(os.path.getsize(f))