Cameron Morris Cameron Morris - 11 days ago 5
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

user_name
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")
f.close()
if Tortilla_option == "yes":
f = open ("user_name.txt","a")
f.write("Tortilla")
f.close()

if Chicken_option == "yes":
f = open ("user_name.txt","a")
f.write("\nChicken")
f.close()

if Salad_option == "yes":
f = open ("user_name.txt","a")
f.write("\nSalad")
f.close()

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

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

Answer

Several things about this code. First:

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

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:
            f.write(item)

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.

Comments