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.
Syntax- open(filename/path,mode)

  1. 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.
  2. 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.

f=open('myfile.txt','w')

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.

f.write(data)

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()

f.close()

Program to take input from user & store in .txt file

To handle the file exceptions, we will enclose our code in try & except block. Sometimes, we may forget to close the file, so we will enclose f.close() in the finally block to avoid errors.

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))

Output:

Enter your data: Hello CodeSpeedy!!

Take input from user and store in .txt file in Python

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:

Leave a Reply

Your email address will not be published.