How to store user input into a file in Python
I'm trying to make a program that takes user input and stores it into a file and I want to know how to do that.
For this, you can use the
open() command in Python.
This is an example, the program ask the user for their name, then add that in a file called
# Ask user for their name username = input("Henlo, what's your name?") # After done the asking, the program opens the file # 'usernames.txt' in write mode, there are some more other # modes, but in this example, I will only use the write mode with open("usernames.txt", "w") as fl: # Now, 'fl' is the reference of the command 'open("usernames.txt", "w")' # The file will write the username that it got # at the first part fl.write(username) # Now, the program done the adding, you should close them fl.close() # That's it!
# Like Wumi, this opens the file, except # now it's in read mode. with open("usernames.txt", "r") as fl: # This stores the contents of the file in a variable data = fl.read() print(data) # IIRC you don't actually need to close # the file, as the `with` block does it # for you.