简体   繁体   中英

Find Largest File and Deleting Folders

I'm working on a cleanup script for tv shows that I download. I want it to get the largest file in each folder, move/rename it and then delete that folder. The issue I'm having is that sometimes when there is another nested folder, it crashes and skips it. I'm not sure how to convert this into a recursive function that does the same functionality. It would also be nice to just look for the largest file instead of use the hard coded 30MB.

Also, sometimes a file I download has an incorrect date so it would be great if it could make each new file the current date and time when the script ran.

import os
import shutil


dir = "C:\Users\Bobe\Downloads\TV\\"

for folder in os.listdir(dir):
    if os.path.isdir(os.path.join(dir,folder)):
        for file in os.listdir(dir + folder):
            filelocation = dir+folder+"\\"+file
            if os.path.getsize(filelocation) > 30000000: # This is in bytes (30 MB)
                extension = os.path.splitext(file)[1]
                shutil.move(filelocation, dir + folder + extension)
            else:               
                os.remove(filelocation)

        shutil.rmtree(dir + folder)

I'm currently learning python :) Thanks for the exercise :D

This should work:

import os
import sys

biggest = ("", -1)
directory = sys.argv[1]

print "Searching", directory

def search(dir):
    global biggest
    for item in os.listdir(dir):
        item = dir + "/" + item
        if os.path.isdir(item):
            search(item)
        else:
            itemsize = os.path.getsize(item)
            if itemsize > biggest[1]:
                    biggest = (item, itemsize)

search(directory)
if biggest[1] != -1:
    print "Found: ", biggest
    # Do something with biggest

Good luck!

Well, the problem was resolved around 12 years ago, but here is a one-liner, maybe it helps somebody. (Not working for subdirectories)

inorder=sorted([[os.path.getsize(os.path.join(folder, x)),os.path.join(folder, x)] for x in os.listdir(folder)])

Output:

biggest = inorder[-1]
smallest = inorder[0]
print(biggest,smallest)
[15794079, 'C:\\Users\\Gamer\\Documents\\Downloads\\volatility_2.6_win64_standalone\\volatility_2.6_win64_standalone\\volatility_2.6_win64_standalone.exe'] [698, 'C:\\Users\\Gamer\\Documents\\Downloads\\volatility_2.6_win64_standalone\\volatility_2.6_win64_standalone\\LEGAL.txt']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM