Nag Venkat
Nag Venkat

Reputation: 41

How to list files in directory and subdirectory based on filesize greater than 10kb using python

I have gone through following scenarios

  1. which we can list files in a directory
  2. Which we can list files with their file sizes

But now I need to list only the files just they are greater than some X KB with the input given by the user.

Please help with some suitable examples

Here is my code

import os 
for path, dirs, files in os.walk("PathToDir" ): 
    for f in files: 
        size=os.path.getsize( os.path.join( path, f ) 
        print path, f, size

Upvotes: 1

Views: 4651

Answers (3)

Amar
Amar

Reputation: 111

I achieved it using the pathlib module. I am running Python 3.7.6 on Windows.

Here's the code:


import os 
from pathlib import Path

dir_path = Path('//?/D:/TEST_DIRECTORY')

# IMP_NOTE: If the path is 265 characters long, which exceeds the classic MAX_PATH - 1 (259) character
# limit for DOS paths. Use an extended (verbatim) path such as "\\\\?\\C:\\" in order 
# to access the full length that's supported by the filesystem -- about 32,760 characters. 
# Alternatively, use Windows 10 with Python 3.6+ and enable long DOS paths in the registry.

# pathlib normalizes Windows paths to use backslash, so we can use
# Path('//?/D:/') without having to worry about escaping backslashes.


F_LIST = list(x for x in dir_path.rglob('*.*') if x.is_file() and os.path.getsize(x) >= 10000)

for f in F_LIST:
    print(f.parts[-1] + " ===> " + "Size = " + str(format(os.path.getsize(f), ',d')) + "\n")

# path.parts ==> Provides a tuple giving access to the path’s various components
# (Ref.: pathlib documentation)

Hope this helps! :-)

Upvotes: 1

GeorgeZ
GeorgeZ

Reputation: 51

Here's an example of how to go 'walk' through the files in a directory, and then printing out the ones that meet a file size criterion:

Note: How to 'walk' was found here:

concatenate the directory and file name

# Task: List only files that are greater than some X KB with the input given by the user.


import os

# The directory that we are interested in
myPath = "/users/george/documents/"

# The min size of the file in Bytes
mySize = '10000'

# All the file paths will be stored in this list
filesList= []

for path, subdirs, files in os.walk(myPath):
    for name in files:
        filesList.append(os.path.join(path, name))

for i in filesList:
    # Getting the size in a variable
    fileSize = os.path.getsize(str(i))

    # Print the files that meet the condition
    if int(fileSize) >= int(mySize):
        print "The File: " + str(i) + " is: " + str(fileSize) + " Bytes"

Upvotes: 4

Louis
Louis

Reputation: 2890

limit = raw_input('Enter a file size: ')
if int(limit) > 0:
    import os 
    for path, dirs, files in os.walk("PathToDir" ): 
        for f in files: 
            size=os.path.getsize( os.path.join( path, f ) 
            if size > limit :
                print path, f, size

Upvotes: 0

Related Questions