首页 > 解决方案 > 如何从引用的行中正确替换文本中的行

问题描述

我编写了一些代码来接收用户并使用文本文件为他们分配任务。我遇到的问题是用户输入要编辑的任务编号,但我不知道如何替换输入的任务编号上方 12 行的文本行,这将替换用户名。如果文本文件中有两个任务,我需要能够使用任务编号行作为参考点,然后将上面的第 12 行替换为新用户名。所以我基本上需要为每个任务替换用户输入上方的第 12 行。我编写了一些代码来替换名称,但它会擦除我的整个文本文件。

文本文件示例:(tasks.txt)

分配给任务的用户:

杰克

任务名称:

任务描述:

飞向月球

任务截止日期:

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

标签: pythonindexingreplaceexternal-data-source

解决方案


这是你想要的?我个人会为此采用熊猫。但这与您的方法一致。

示例输入文件:

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" ')

输出/输出

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" 

推荐阅读