Thursday, November 28, 2024
Google search engine
HomeLanguagesTake input from user and store in .txt file in Python

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

In this article, we will see how to take input from users and store it in a .txt file in Python. To do this we will use python open() function to open any file and store data in the file, we put all the code in Python try-except block. Let’s see the implementation below.

Stepwise Implementation 

Step 1: First, we will take the data from the user and store it in a temporary variable ‘temp’.

Step 2: We will open the file with the file name using the Python open() function with the write mode enabled.

Note: If the file doesn’t exist it will automatically create the file for us.

# this means the file will open
# with write mode enabled
x = open(gfg.txt,w)

Step 3: Now we will write the data into the file we just created.

x.write(temp)

Step 4: Finally, we will keep the file operations under a try-except block to check for exceptions.

Example 1:

Python3




temp = input("Please enter your information!!   ")
try:
    with open('gfg.txt', 'w') as gfg:
        gfg.write(temp)
except Exception as e:
    print("There is a Problem", str(e))


Output:

 

gfg.txt

Example 2:

Python3




temp = input("Please enter your information!!   ")
try:
    with open('gfg.txt', 'w') as gfg:
        gfg.write(temp)
except Exception as e:
    print("There is a Problem", str(e))


Output:

input text

gfg.txt

RELATED ARTICLES

Most Popular

Recent Comments