Take input from user and store in .txt file in Python
Hello Geek! In this article, we will learn how to take input from the user and store it in a .txt file in Python. File handling in Python is a lot easier when compared to other programming languages. So let us learn this program in a simple way.
Python program to take input from user & store in .txt file
First of all, we will take the input from the user and we will store that input in a variable called data.
data=input("Enter your data:")
Now, we will open a file using the inbuilt open( ) method which returns the file object. This file object is used to read data from the file or write data into the file.
This method has two string parameters: filename/path and mode.
- filename/path – We will specify the complete path of the file. If we just specify the filename, it opens the file in the current directory. Let us suppose that, ‘myfile.txt‘ is our desired file in the current directory.
- mode – We will specify the mode as ‘w’ (write). It overwrites the data in the ‘myfile.txt‘ file. If that file doesn’t exist, it creates a new file.
Here f is a reference to the file object.
Now, we will pass data to the f.write( ) method which inserts our data into the file. It has a single parameter: data
Syntax – fileobject.write(data)
Here, data is the user input that we stored in the data variable.
At last, we will close the file using the inbuilt close() method. If we don’t close the file, the data won’t make it to the target file.
Syntax – fileobject.close()
Program to take input from user & store in .txt file
data=input("Enter your data:") try: f=open('myfile.txt','w') f.write(data) except Exception as e: print("Error:",str(e)) finally: f.close()
Instead of using f.close() in the finally block, we can also open the file using with statement which automatically closes the file when we are done with it.
data=input("Enter your data:") try: with open('myfile.txt','w') as f: f.write(data) except Exception as e: print("Error:",str(e))
Enter your data: Hello CodeSpeedy!!
That’s it! Hope you found this helpful.
If you face any problems feel free to post them below.
Also, do check our other articles: