这是你想要的?我个人会为此采用熊猫。但这与您的方法一致。
示例输入文件:
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"