0

I have the following script:

import os
import stat

curDir = os.getcwd()+'/test'

for (paths, dirs, files) in os.walk(curDir):
        for f in files:
            if os.stat(f)[stat.ST_SIZE]>0:
                print f

and the folder test/:

test_folder:
    --test.wav
a.exe
t1
t2
rain.wav

when i run this script with geany it gives the following error:

Traceback (most recent call last):
  File "new_folder_deleter.py", line 8, in <module>
   if os.stat(f)[stat.ST_SIZE]>0:
   OSError: [Errno2] No such file or directory: 'a.exe'

but when I run it with IDLE: it just prints test.wav in subfolder test_folder

Can anyone explain why it is so and how I can fix it? P.S: My aim is to browse all files and delete files with specified sizes.

1
  • Have you tried doing this - os.stat( os.path.join(paths, f) ) instead of just os.stat( f ) Commented Sep 12, 2011 at 13:23

4 Answers 4

1

You need to specify a full path for os.stat, unless the file is in the current working directory. The simplest way to fix this is to change the WD before trying to access the files:

curDir = os.getcwd()+'/test'
os.chdir(curDir)

A more general solution is to pass the full path to os.stat:

if os.stat(os.path.join(paths, f))[stat.ST_SIZE]>0:
  print f

I am not quite sure why IDLE does not produce an error here, though.

Sign up to request clarification or add additional context in comments.

Comments

0

The filename is only the basename. You need to use os.path.join(path, f).

Comments

0

The list of files that's returned in the files component from os.walk() is just the file names, without the path. Before you can perform any operations on those files (including stat()), you need to reassemble the path to the file.

Comments

0

The os.walk function returns file and directory names relative to current folder, so you need to os.stat(os.path.join(paths, f)).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.