1

I want to print filenames and their directory if their filesize is more than a certain amount. I wrote one and set the bar 1KB, but it doesn't work even if there are plenty of files larger than 1KB.

import os, shutil

def deleteFiles(folder):
    folder = os.path.abspath(folder)

    for foldername, subfolders, filenames in os.walk(folder):
         for filename in filenames:
            if os.path.getsize(filename) > 1000:
                print(filename + ' is inside: ' + foldername)

deleteFiles('C:\\Cyber\\Downloads')

And I got 'Nothing'!

and then I wrote codes in interactive shell, I got following error:

Traceback (most recent call last):
   File "<pyshell#14>", line 3, in <module>
      if os.path.getsize(filename) > 100:
   File "C:\Users\Cyber\Downloads\lib\genericpath.py", line 50, in getsize
    return os.stat(filename).st_size
 FileNotFoundError: 

I am wondering How I can fix my code.

2 Answers 2

0

os can't find the file without a given path, following your code, you have to re-specify the absolute path. Replace

if os.path.getsize(filename) > 1000:

with

if os.path.getsize(os.path.abspath(foldername + "/" + filename)) > 1000:

And it should work.

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

1 Comment

Thank you!! i didn't know i need to insert /
0

Replace:

deleteFiles('C:\\Cyber\\Downloads')

with

import os

a = 'c:' # removed slash
b = 'Cyber' # removed slash
c = 'Downloads'

path = os.path.join(a + os.sep, b, c)
deleteFiles(path)

2 Comments

The book does not go too deep into OS-specific paths, so Windows paths are handled this way.
Welcome. This helps to let Python compute the right path and not trying to guess if forward slash or back slash should be used to properly construct it.

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.