如何根据输入正确替换文本文件中的数据

How to correctly replace data in text files based on input

我有以下问题。我正在尝试根据性别输入替换名称。如果有人可以帮助改进我的代码,将不胜感激。

文本文件(duedate.txt):

User: Tommy

Gender: Male

Date due: 2020-02-18

我目前的代码是:

with open f = ('duedate.txt).read()
    z = input("Please select gender to change) 
    zz = input("Please select new name")
    if z == 'female' 
       line.startswith('User'): 
       field, value = line.split(:) 
       value = zz
       print (zz) 

我知道代码不是 100% 正确,但如果选择 Jessica 作为名字,输出应该是:

User: Jessica

Gender: Female

Date due: 2020-02-18

这应该有效。注释中给出代码解释:


import pandas as pd
import numpy as np

# Read the text file into a dataframe
df = pd.read_csv('duedate.txt', sep = "\n",header=None)

# Do dataframe manipulations
df[['Variable','Value']] = df[0].str.split(':',expand=True)
del df[0]

# Collect inputs from user:
z = input("Please select gender to change")
zz = input("Please select new name")

# modify dataframe based on user inputs
df.loc[0,"Value"]=zz
df.loc[1,"Value"]=z

#Construct output column
df["Output"] = df["Variable"] + ": " + df["Value"] + "\n"

# Save the file back to disk
np.savetxt(r'duedate.txt', df["Output"].values,fmt='%s')