Cameron Morris Cameron Morris - 1 year ago 102
Python Question

How to rename a text file with user input

I am trying to code my own food selector in python where people can pick if they want a tortilla in their wrap for example and the program will work out the costs.

One of the extra's I am trying to do is that, if the customer does not want to checkout immediately they can save their order to a text file. That all works perfectly but how do I rename this text file to the

so that only their choices are displayed and so I know who has made these choices?

if order_save =="1":

f = open ("user_name.txt","w")
if Tortilla_option == "yes":
f = open ("user_name.txt","a")

if Chicken_option == "yes":
f = open ("user_name.txt","a")

if Salad_option == "yes":
f = open ("user_name.txt","a")

if Chilli_option == "yes":
f = open ("user_name.txt","a")
f.write("\nChilli Sauce")

print ("Here is your takeway that will be saved",user_name,"!\n")
f = open ("user_name.txt","r")

Answer Source

Several things about this code. First:

f = open ("user_name.txt","a")
f.write("\nChilli Sauce") 

can be written as

with open(user_name+'.txt', 'a') as f:
    f.write('\nChilli Saurce')

that manages the closing of the file automatically. It's called a context manager

Also, that saves the order into a file the name of which depends on who the user is. Notice that user_name is the variable, not a string.

However, a better strategy would be do define a function:

def write_order(user, item, option_yes_or_no):
    if option_yes_or_no=='yes':
        with open(user+'.txt', 'a') as f:

and then you replace the whole thing with:

for my_option in [tortilla_option, chicken_option, salad_option]:
    write_order(user_name, item, my_option)

which avoids duplicating a lot of code.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download