Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search file by its size using Python [duplicate]

Tags:

python

linux

I have gotten stuck. I need to write code using Python to find a file by its size and add its name and size to a list. I have a program which searches a directory for a file by name. I need to make another flag with get opts to do a search by size.

import getopt
import sys
import os
from os import listdir, walk
from os.path import isfile, join

def find_by_name(name, path, result): #Define a function to search the file by it's name
    result = []
    for root, dirs, files in os.walk(path):
        if name in files:
            result.append(os.path.join(name)) #Join the file to the list called result
        else:
            print ("Nothing was found by %s" % name)
        return result
def main():
    path_dir = raw_input("Select the directory you want to search: ")
    results = []
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'n:y:d:')
    except getopt.GetoptError as err:
        print (err)
        sys.exit

    for o, a in opts:
        if o in ("-n", "--name"):
           pro = find_by_name(a, path_dir, results)
if __name__ == "__main__":
    main()
like image 641
Jade Avatar asked Dec 18 '25 14:12

Jade


2 Answers

os.walk gives you the path and filename. you can then use

stats = os.stat(path+name)
stats.st_size

to get the file size in bytes. so you could just change up your current function to something like:

def find_by_size(size, path):
    result = []
    for root, dirs, files in os.walk(path):
        if os.stat(path+name).st_size == size:
            result.append((os.path.join(name), stats.st_size))
        else:
            print ("Nothing of size %d was found" % size)
        return result

also you don't need to pass result in, since you're just replacing it with an empty list. Python can return lists from a function.

like image 129
Jonathan Eskritt Avatar answered Dec 21 '25 06:12

Jonathan Eskritt


def matched_files(base_directory):
    for root, dirs, files in os.walk(path):
        if name in files:
           yield os.path.join(root,name) #Join the file to the list called result

print sorted(matched_files("/some/path"),key=os.path.getsize) #sort files matching name by size

I think will work ... plus it simplifies your matching program alot ... by turning it into a generator

if you are trying to match all files that are a given size regardless of name ... this might not be the best solution ... but you could probably make it work easy enough

really if you want to find all files of a certain size ... just plain old bash/sed/awk would probably work best

like image 24
Joran Beasley Avatar answered Dec 21 '25 05:12

Joran Beasley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!