Created
January 29, 2023 05:42
-
-
Save dmoruzzi/2a62801d5d4e5bb538b30bd1174c3edf to your computer and use it in GitHub Desktop.
Lists file information from a specified directory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import argparse | |
from datetime import datetime | |
def get_file_info(dir_path: str = ".", extensions: tuple = None) -> list: | |
try: | |
file_list = [] | |
for entry in os.scandir(dir_path): | |
if extensions: | |
if not entry.name.endswith(extensions): | |
continue | |
file_info = {} | |
file_info["file"] = entry.name | |
file_info["modified_date"] = datetime.fromtimestamp(entry.stat().st_mtime).strftime("%Y-%m-%d %H:%M:%S") | |
file_info["size"] = entry.stat().st_size | |
file_info["file_type"] = entry.name.split(".")[-1] | |
file_info["is_file"] = entry.is_file() | |
file_info["is_dir"] = entry.is_dir() | |
file_info["is_symlink"] = entry.is_symlink() | |
file_list.append(file_info) | |
return file_list | |
except FileNotFoundError: | |
print(f"{dir_path} not found.") | |
return [] | |
if __name__ == "__main__": | |
parser = argparse.ArgumentParser(description='List file information') | |
parser.add_argument('dir_path', type=str, nargs='?', default='.', help='directory path') | |
parser.add_argument('-e','--extensions', type=str, nargs='+', help='file extensions') | |
args = parser.parse_args() | |
print(get_file_info(args.dir_path, tuple(args.extensions) if args.extensions else None)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment