Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Python to find the largest file quickly

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the knowledge of "how to use Python to find the largest file quickly". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Idea: we traverse the directory, return the file path and file size as a generator, then insert a large top heap with a size of 10, and finally print the contents of the big top heap.

With Python, the code is simple:

Import os import time from os.path import join, getsize from heapq import nlargest def walk_files_and_sizes (start_at: str): for root, _, files in os.walk (start_at): for file in files: path = join (root, file) try: size = getsize (path) # bytes yield path Size except OSError: continue def largest_files (n: int, start_at: str)-> None: MB = 1024 * 1024 largest = nlargest (n, walk_files_and_sizes (start_at), key=lambda x: X [1]) for path Size in largest: print (f'{size//MB} MB {path}') if _ _ name__ = ='_ _ main__': start = time.perf_counter () largest_files (10, "/ Users/aaron/") elapsed = time.perf_counter ()-start print (f'{elapsed} seconds elapsed')

I ran down a directory of about 200 GB on my computer in 123 seconds:

Then delete the files you don't need.

If it is a Windows system, it is also possible:

Largest_files (10, "C:/Users/xxx/") "how to use Python to quickly find the largest file" content is introduced here, thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report