Создание файла из терминала с помощью input(), бесконечного цикла, os.makedirs, по условиям
from datetime import datetime
from sys import argv
from os import mkdir, chdir
filename = ""
directories = []
if "-f" in argv:
index = 0
for _ in range(len(argv) - 1):
index += 1
print(index)
if argv[_: _ + 1] == ["-f"]:
break
filename = argv[index]
if "-d" in argv:
index2 = 0
for _ in range(len(argv) - 1):
index2 += 1
if argv[_: _ + 1] == ["-d"]:
break
directories = argv[index2:index - 1]
else:
filename = "file.txt"
if "-d" in argv:
index = 0
for _ in range(len(argv) - 1):
index += 1
if argv[_: _ + 1] == ["-d"]:
break
directories = argv[index:len(argv)]
file_data = [datetime.today().strftime('%y:%d:%m %H-%M-%S'), "\n"]
while True:
line = input("Enter content line: ")
if line == "exit":
break
file_data.extend([line])
for directory in directories:
try:
mkdir(directory)
except Exception:
pass
chdir(directory)
with open(filename, "w") as f:
f.writelines(file_data)
Написала такой код, но не доконца понимаю логику задачи, условие такое: Create file from terminal Create an app create_file.py that takes directory path, file name, file content from the terminal and creates file. There should be flags -d or -f: If only -d flag passed, means all items after this flag are parts of the path. python create_file.py -d dir1 dir2 - creates directory dir1/dir2 inside current directory. If only -f flag passed, means first item is the file name. python create_file.py -f file.txt After pressing Enter it creates file file.txt and then terminal should ask you to input content lines until you input "stop": Enter content line: Line1 content Enter content line: Line2 content Enter content line: stop This creates file file.txt inside current directory with content: 2022-02-01 14:41:10 1 Line1 content 2 Line2 content
App should add current timestamp at the top and number lines. If file.txt already exists it should add content below: python create_file.py -f file.txt Enter content line: Another line1 content Enter content line: Another line2 content Enter content line: stop 2022-02-01 14:41:10 1 Line1 content 2 Line2 content
2022-02-01 14:46:01 1 Another line1 content 2 Another line2 content
If both -d and -f flags passed, app creates directory and file with content inside this directory. python create_file.py -d dir1 dir2 -f file.txt Enter content line: Line1 content Enter content line: Line2 content Enter content line: stop Creates directory dir1/dir2 inside current directory and creates file file.txt inside that directory with content: dir1/dir2/file.txt: 2022-02-01 14:46:01 1 Line1 content 2 Line2 content
Вопросы:
- Не понимаю что нужно передавать в аргументы к. строки? argv = ['-f', '-d', '-f-d'] - верно или нет?
- Какова должна быть логика работы, сразу весь список argv читаем, потом вводим данные в консоль или прочитали один елемент списка ввели данные в консоль , прочитали второй - ввели данные? Наверное как-то по другому должно работать, но не пойму как?