0

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

Community
  • 1
  • 1
NoobDev88
  • 23
  • 6

1 Answers1

1

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')
Karthick Mohanraj
  • 1,565
  • 2
  • 13
  • 28
  • Thank you guys for the suggestions! As soon as im back at my PC I'm going to give them a go. Thank you@alec and thank you @Karthick – NoobDev88 Feb 20 '20 at 09:42
  • Hey @Karthick. Can I please ask you a quick question... Ive typed the code out exactly but im getting an error saying: No module named 'pandas' – NoobDev88 Feb 20 '20 at 11:28
  • 1
    @NoobDev88 You have to install pandas package using the pip command in your python environment as "pip install pandas". You can refer to the docs here: https://pypi.org/project/pandas/ – Karthick Mohanraj Feb 20 '20 at 11:40
  • Thank you so much @Karthic it works perfectly... Just one more question. If I have more than one user and a line sepperates the two. Its leaving "nan" between the lines... Any idea how to remove this? – NoobDev88 Feb 20 '20 at 12:04
  • @NoobDev88 Could you re-edit the question to show a sample of the input? – Karthick Mohanraj Feb 20 '20 at 12:21
  • I was able to fix it... Was a problem on my side with new lines. Last question is it possible to only edit a second user without changing the first – NoobDev88 Feb 20 '20 at 13:49