Take user input and save those in .txt file using Python
In this tutorial, we will learn how can we take input from users and save these inputs into a .txt file. These types of things are useful for developers as they need to store the data of users for various reasons.
Python provides flexibility with variation to implement such kind of mechanism.
In Python, Take user input and save those in a .txt file
Now let’s see how to do this with one simple example,
def main(): outfile = open("data.txt","w") fname = input("Please enter your first name: ") lname = input("Please enter your last name: ") outfile.write(fname) outfile.write("\t") outfile.write(lname) outfile.close() main()
Here, we have defined a function main in which first of all, we will create a file (data.txt) in which we will store the first name and last name of the user.
In Python, we use the key function open( ) which can work with files. This open( ) will take two functions filename and mode.
When it comes to opening a file, there are four options:
“r” will read the default value and open a file for reading, if the file does not exist then it will show an error. “a” will open a file for appending, and if the file does not exist then it creates one. “x” will create the specified file and if the file exists then it will show an error.”w” will opens a file for writing and if the file does not exist then it creates one.
Now, outfile.write(fname) and outfile.write(lname) will write first name and last name of user in data.txt file. In addition to that outfile.write(“\t”) will apply space between first name and last name as shown below.
Please enter your first name: Yashkumar Please enter your last name: Patel
In file (data.txt), it will show as below,