Reputation: 8079
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.
Upvotes: 0
Views: 2038
Reputation: 2173
The os.walk
function returns file and directory names relative to current folder, so you need to os.stat(os.path.join(paths, f))
.
Upvotes: 0
Reputation: 36504
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.
Upvotes: 0
Reputation: 6647
The filename is only the basename. You need to use os.path.join(path, f)
.
Upvotes: 0
Reputation: 95308
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.
Upvotes: 1