CountFolderFiles/CountFolderFiles.py

105 lines
4.1 KiB
Python

import os
import sys
from pathlib import Path
def append_to_folder_name(folder_path, suffix):
try:
# Get the base folder name
base_folder_name = os.path.basename(folder_path)
# Append the suffix to the folder name
new_folder_name = f"{base_folder_name} [{suffix}]"
# Rename the folder
os.rename(folder_path, os.path.join(os.path.dirname(folder_path), new_folder_name))
print(f"Folder renamed to: {new_folder_name}")
except FileNotFoundError:
print(f"Error: Unable to rename folder '{folder_path}'.")
os.system("pause")
def get_subdirectories(folder_path):
subdirectories = []
for entry in os.scandir(folder_path):
if entry.is_dir():
subdirectories.append(entry.path)
return subdirectories
def count_subdirectories(path):
return sum(1 for dir in Path(path).iterdir() if dir.is_dir())
def count_folder_files(folder_path):
try:
# If no subfolders exist, return the number of files in the folder
num_subdirectories = count_subdirectories(folder_path)
if num_subdirectories == 0:
# Count the number of files in the folder
file_count = sum(1 for entry in os.scandir(folder_path) if entry.is_file())
print(f"Number of files in the folder: {file_count}")
return file_count
# If subdirectories do exist, return the number of files in each subdirectory then this directory
else:
file_count = ""
subdirectories = get_subdirectories(folder_path)
for i, directory in enumerate(subdirectories):
file_count = file_count + str(sum(1 for entry in os.scandir(directory) if entry.is_file()))
#If there's another element, add a space (Keep code this way so that append folder files looks right)
if i != len(subdirectories) - 1:
file_count = file_count + " "
#Append the number of files in the folder unless if there are none
if (sum(1 for entry in os.scandir(folder_path) if entry.is_file()) > 0):
file_count = file_count + " " + str(sum(1 for entry in os.scandir(folder_path) if entry.is_file()))
print(subdirectories)
print(file_count)
return file_count
except FileNotFoundError:
print(f"Error: Folder '{folder_path}' not found.")
os.system("pause")
def check_directory_exists(directory_name):
return os.path.isdir(directory_name)
def clean_directory_name(directory_name):
if '\\' in directory_name:
# Find the last occurrence of backslash
last_backslash_index = directory_name.rfind('\\')
# Find the first occurrence of '[' after the last backslash
last_open_bracket_index = directory_name.find(' [', last_backslash_index)
# If '[' exists after the last backslash, remove everything after it
if last_open_bracket_index != -1:
return directory_name[:last_open_bracket_index]
else:
# If '[' doesn't exist, keep the original string
return directory_name
else:
return directory_name.rsplit(" [", 1)[0]
def main():
if len(sys.argv) < 2:
print("Usage: CountFolderFiles <folder_path>")
sys.exit(1)
args = sys.argv[1:]
for arg in args:
directory_name = arg
suffix = count_folder_files(directory_name)
# If [num] already exists at the end of the string, remove it so we can update it
directory_name_cleaned = clean_directory_name(directory_name)
if check_directory_exists(directory_name):
print(f"Directory '{directory_name}' exists.")
#If folder was counted already, remove the old count. Ex: dirname_[1] -> dirname
os.rename(directory_name, os.path.join(os.path.dirname(directory_name), directory_name_cleaned))
directory_name = directory_name_cleaned
append_to_folder_name(directory_name, suffix)
else:
print(f"Directory '{directory_name}' does not exist.")
if __name__ == "__main__":
main()