Question: Python: Need file to be automatically created but also use r+ mode I have the following program that takes user input each time it is
Python: Need file to be automatically created but also use r+ mode
I have the following program that takes user input each time it is run and adds it to a list, then remembers it the next time the program is run and does not allow duplicate values. The issue is that in r+ mode the program will give an error if the file "colorfile" does not already exist. I want it to create the file automatically but retain its functions. How can I do this?
Here is my code:
colors = [] with open("colorfile", "r+") as f: for line in f: colors.append(line.strip())
while True: color = input("add a color to the colors: ").lower().strip() if color not in colors: colors.append(color) f.write(color + " ") break else: print("color already exists, try again")
print(colors)
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
