- The
run function is entirely superfluous. Get rid of it.
- Comments like
# # # # # Functions # # # # # are also extraneous.
- Use context managers when opening files.
- Print error messages to
sys.stderr. This allows the user to redirect that output if they so desire.
- Messages like
"End of script." are almost certainly extraneous, unless specifically stated as requirements.
- You can write your checks of input as guards and return early from the function, reducing conditional nesting. This is a matter of taste.
- Specifying the
folder=FOLDER given that there's one argument, and the keyword and the argument have the same name seems superfluous.
- The wording of your second error message, "Choose another filename or delete existing file." suggests further user interaction, but instead the program just ends. You may wish to reword this.
Further, having write_into_file directly handle printing error messages may be giving it too much to do. Rather we can have it return custom exceptions (if the standard library does not provide a suitable exception) and let the caller determine how to deal with these situations.
E.g.
from pathlib import Path
from sys import stderr
class IncorrectExtensionException(Exception):
def __init__(self, expected_ext, filename):
super().__init__()
self.expected_ext = expected_ext
self.filename = filename
class FileAlreadyExistsException(Exception):
def __init__(self, filename):
super().__init__()
self.filename = filename
def write_into_file(folder, file_name:str="stats_dossiers.txt") -> None:
if not file_name.endswith(".txt"):
raise IncorrectExtensionException(".txt", file_name)
new_file = Path(folder, file_name)
if new_file in folder.iterdir():
raise FileAlreadyExistsException(new_file)
with open(new_file, "w", encoding="utf-8") as stats_folder:
print(f"The file {new_file} was created with success")
stats_folder.write("Name of folder ; Weight (Byte) \n")
for file in folder.iterdir() :
name = str(file)
size = file.stat().st_size
stats_folder.write(f"{name} ; {size} \n")
if __name__ == "__main__":
try:
write_into_file(FOLDER)
except IncorrectExtensionException as e:
print(f"{e.filename} is not a {e.expected_ext} format. Choose another file in {e.expected_ext} format.", file=stderr)
except FileAlreadyExistsException as e:
print(f"The file {e.filename} already exists. Choose another filename or delete existing file.", file=stderr)