Skip to content
Open
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 72 additions & 1 deletion app/create_file.py
Original file line number Diff line number Diff line change
@@ -1 +1,72 @@
# write your code here
import sys
import os
from datetime import datetime
from typing import List, Optional


def create_directory(dirs: List[str]) -> str:
if not dirs:
return ""

path: str = os.path.join(*dirs)
os.makedirs(path, exist_ok=True)
return path


def create_file(file_path: str) -> None:
timestamp: str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
content_lines: List[str] = []

line_number: int = 1

while True:
line: str = input("Enter content line: ")
if line.lower() == "stop":
break
content_lines.append(f"{line_number} {line}")
line_number += 1

if not content_lines:
return

content: str = timestamp + "\n" + "\n".join(content_lines)

file_exists: bool = os.path.exists(file_path)

with open(file_path, "a") as f:
if file_exists:
f.write("\n\n")
f.write(content)


def main() -> None:
args: List[str] = sys.argv[1:]

dirs: List[str] = []
filename: Optional[str] = None

if "-d" in args:
d_index: int = args.index("-d")

if "-f" in args:
f_index: int = args.index("-f")
dirs = args[d_index + 1:f_index]
else:
dirs = args[d_index + 1:]
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Critical bug: When -f appears before -d (e.g., ["-f", "file.txt", "-d", "dir1"]), this slice produces empty list since start index (4) > end index (0). This prevents directory creation when flags are in this order.


if "-f" in args:
f_index: int = args.index("-f")
try:
filename = args[f_index + 1]
except IndexError:
return

path: str = create_directory(dirs)

if filename:
file_path: str = os.path.join(path, filename) if path else filename
create_file(file_path)


if __name__ == "__main__":
main()
Loading