Как правильно заменить строку в тексте из указанной строки - PullRequest
0 голосов
/ 18 февраля 2020

Я написал некоторый код, чтобы принимать пользователей и назначать им задачи с помощью текстового файла. Проблема, с которой я сталкиваюсь, заключается в том, что пользователь вводит номер задачи для редактирования, но я не знаю, как заменить строку текста на 12 строк выше введенного номера задачи, и это заменяет имя пользователя. Если в текстовом файле есть две задачи, мне нужно иметь возможность использовать строку номера задачи в качестве контрольной точки, а затем заменить 12-ю строку над ней новым именем пользователя. Поэтому мне нужно заменить 12-ю строку над вводом пользователя для каждой задачи. Я написал некоторый код, чтобы просто заменить имя, но оно стирает весь мой текстовый файл.

Пример текстового файла: (tasks.txt)

Пользователь назначен на задачу:

jack

Название задачи:

Полет

Описание задачи:

Полет на Луну

Дата выполнения задачи:

2020-02-20 Назначенная дата:

2020-02-18

Задание выполнено:

Нет

Номер задания:

1

Код действующего блока на данный момент:

with open('tasks.txt') as xxaz:
                 main2 = "Task number:" + "\n" + str(review)
                 aa = xxaz.read()
                 if main2 in aa:
                         print(str(main2) + "\n")
                         edit = input("Enter ""1"" to edit the user assigned to task, ""2"" to change the due date or ""3"" to change the completion status.\n")
                         if edit == "1":
                             new_name = input("Please enter a new user name")
                             lines = open('tasks.txt').read().splitlines()
                             lines[2] = new_name
                             open('tasks.txt','w').write

Ответы [ 2 ]

0 голосов
/ 18 февраля 2020

Это то, что вы ищете? Лично я приму pandas для этого. Но это соответствует вашему подходу.

Пример входного файла:

User assigned to task:
jack
Task Title :
Fly
Task Description:
Fly to the moon
Task Due Date:
2020-02-20
Date Assigned:
2020-02-18
Task Completed:
No
Task number:
1
User assigned to task:
jill
Task Title :
Walk
Task Description:
Walk to the moon
Task Due Date:
2020-03-20
Date Assigned:
2020-02-19
Task Completed:
No
Task number:
2
User assigned to task:
Brenda
Task Title :
Run
Task Description:
Run to the moon
Task Due Date:
2020-03-16
Date Assigned:
2020-04-19
Task Completed:
Yes
Task number:
3

Код

#Take the user inputs
review = input('Enter the task number you want to modify: ')
field = input('''Enter:
1: To change the user assigned to task.
2: To change the due date.
3: To change the completion status
''')
value = input('Enter the value: ')

#Create a function which returns the field name as per the number provided by the user
def switchdic(num):
    dic = {'1':'User assigned to task:',
          '2':'Task Due Date:',
          '3':'Task Completed:'
          }
    return dic.get(num,'Invalid entry')

#code block to read and write the modified content to a new file
with open('user_task_data.txt') as fh,open('new_task_data.txt','w') as fw :
    lines = fh.readlines()
    for line in lines:
        #Skip the lines if they do not match the 'Task number:' as the previous line
        if (lines[lines.index(line)-1].strip() != "Task number:"):
            continue
        data = lines[lines.index(line)-13:lines.index(line)+1] #Assign the whole block of the given task number to variable data
        #Modify the values as per the given input and write to the new file
        if review == str(line.strip()):
            data[lines.index(switchdic(field)+"\n")+1] = value+"\n"
            fw.write(''.join(data))
        #Write the values as they are if they are not connected to the input task number
        else:
            fw.write(''.join(data)) 
print('The file is modified and new file is"new_task_data.txt" ')

O / P

Enter the task number you want to modify: 3
Enter:
1: To change the user assigned to task.
2: To change the due date.
3: To change the completion status
3
Enter the value: No
The file is modified and new file is"new_task_data.txt" 
0 голосов
/ 18 февраля 2020

Вот решение, если вы хотите продолжить использовать тот же подход:

Tasks.txt:

User assigned to task:
jack
Task Title :
Fly
Task Description:
Fly to the moon
Task Due Date:
2020-02-20 Date Assigned:
2020-02-18
Task Completed:
No
Task number:
1
User assigned to task:
qwe
Task Title :
Fly
Task Description:
Fly to the moon
Task Due Date:
2020-02-20 Date Assigned:
2020-02-18
Task Completed:
No
Task number:
2

Код: -

with open(r"C:\Users\xyz\Desktop\Tasks.txt","r+") as xxaz:
    main2 = "Task number:" + "\n" + str(2)
    if main2 in xxaz.read():
        edit = input("Enter ""1"" to edit the user assigned to task, ""2"" to change the due date or ""3"" to change the completion status.")
        if edit == "1":
            xxaz.seek(0)
            taskLines = xxaz.readlines()
            new_name = input("Please enter a new user name: ")
            for i in taskLines:
                if i == ('Task number:\n'):
                    indexVal = taskLines.index('Task number:\n')
                    taskLines.insert(indexVal,taskLines[indexVal]+taskLines[indexVal+1])
                    taskLines.pop(indexVal+1)
                    taskLines.pop(indexVal+1)
            indexVal = taskLines.index(main2.strip())
            taskLines.pop(indexVal-10)
            taskLines.insert(indexVal-10,new_name+'\n')
            xxaz.seek(0)
        xxaz.writelines(taskLines)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...