0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

<Python>ファイルサイズ上位10個をリストアップする

Posted at

まえがき

こちらの関連です。今回はファイルサイズの上位10個を表示させます。
1GB以上のファイルを探す

ファイルサイズが大きい上位10個を表示する

import os
import datetime
import math

#file_unitはファイルサイズ単位を適切に判断するための処理です。
#少数点第二位までを表示させます。
#人間が読みやすいようにファイルサイズによって単位を変更します。
def file_unit(size_bytes):
	units=["B", "KB", "MB", "GB", "TB"]
	i = math.floor(math.log(size_bytes, 1024)) if size_bytes > 0 else 0
	size = round(size_bytes /1024 ** i, 2)
	return f"{size}{units[i]}"


#list_filesはファイルサイズが1GB以上のファイルを出力する処理です。
#file_size >= 1 * 1024 * 1024 * 1024 によってファイルサイズを計算しています。1024を1回掛けるごとにファイルサイズが1KB,1MB,1GBというように変化します。
#表示はファイルフルパス、タイムスタンプ、ファイルサイズを表示します。
#base_dir,root,dirs
def list_files(base_dir):
	file_info_list=[]
	for root, dirs, files in os.walk(base_dir):
		for file_name in files:
			file_path = os.path.join(root, file_name)
			if os.path.isfile(file_path):
				file_size = os.path.getsize(file_path)
				if file_size >= 1 * 1024 * 1024 * 1024:
					mtime = os.path.getmtime(file_path)
					timestamp = datetime.datetime.fromtimestamp(mtime).strftime('%Y/%m/%d')
					file_info_list.append({
						"path": file_path,
						"timestamp": timestamp,
						"size": file_size
					})
	if file_info_list==[]:
		print("file over 1GB was not found")
	for info in file_info_list:
		size_str = file_unit(info["size"])
		print(info["path"])
		print(info["timestamp"])
		print(size_str)
		print()

if __name__ == "__main__":
	TARGET_DIR = "."                 #任意のフォルダを指定してください。
	list_files(TARGET_DIR)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?