Skip to content
Sign upLog in
← Back to Community

How to store user input into a file in Python

Profile icon
asfdfg

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.

Answered by SixBeeps [earned 5 cycles]
View Answer
Voters
Profile icon
asfdfg
Comments
hotnewtop
Profile icon
Wumi4

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 usernames.txt:

# 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!
Profile icon
asfdfg

@Wumi4

Thanks, that really helped!

Profile icon
asfdfg

How to bring back that file when I need to use it?

Profile icon
SixBeeps

@asfdfg
something like this

# 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.
Profile icon
[deleted]

You should be able to learn how to do what you want from this page: https://www.programiz.com/python-programming/file-operation