Search code examples
pythonexternal-data-source

How to correctly replace data in text files based on input


I have the following problem. Im trying to replace the name based on the input of gender. If anyone could help improve my code it would be really appreciated.

The text file(duedate.txt):

User: Tommy

Gender: Male

Date due: 2020-02-18

The code I have so far is:

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) 

I know the code isn't 100% right but the output, if Jessica was chosen as the name, should be:

User: Jessica

Gender: Female

Date due: 2020-02-18


Solution

  • This should work. Code explanation is given in the comments:

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