Let me add some additional suggestions:
Allow Arguments to write_into_file Be Path or str
- For greater flexibility you should allow the arguments to
write_into_file be a string or Path instance.
- It is also possible that the passed
file_name argument refers to an exiting directory rather than a file. In this case a distinct exception should be raised.
- Since the second argument to
write_into_file can be a Path instance or a string, a better name for it is file.
- The current code will adds statistics for the file being created (i.e. itself) showing a 0 byte length since it has not yet been closed. We should skip reporting for this file.
Putting it all together (based on the post by Chris):
#encoding:utf-8
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
class FileIsADirectoryException(Exception):
def __init__(self, filename):
super().__init__()
self.filename = filename
def write_into_file(folder:str|Path=".", file:str|Path="stats_dossiers.txt") -> None:
folder = Path(folder) # ensure it is a path
file = Path(file) # ensure it is a Path
# Check if file is .txt format:
if file.suffix != ".txt":
raise IncorrectExtensionException(".txt", file)
new_file = Path(folder, file)
if new_file.is_file():
raise FileAlreadyExistsException(new_file)
if new_file.is_dir():
raise FileIsADirectoryException(new_file)
with new_file.open("w", encoding="utf-8") as stats_folder:
print(f"The file {new_file} was created with success.", file=stderr)
stats_folder.write("Name of folder ; Weight (Byte)\n")
for file in folder.iterdir():
if file == new_file:
continue # No point in reporting on this file
size = file.stat().st_size
# Write into a file name of folder and its weight:
stats_folder.write(f"{file} ; {size}\n")
if __name__ == "__main__":
try:
write_into_file()
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)
except FileIsADirectoryException as e:
print(f"The file {e.filename} specifies an existing folder. Choose another filename.", file=stderr)
`write_into_file` will *mostly* work if the `folder` and/or `file_name` arguments are either a string or a `Path` instance (if `file_name` is a `Path` instance, then you would need to convert this to a string So I would suggest that your type hints should reflect that. It also follows that argument `file_name` should be renamed to `file` since its current name suggests its type is a string:
```python
## Improved Checking
Function `write_into_file` is passed a file