Home »
Python
Python | Input data from the user, save to the file, read and print
In this tutorial, we are going to learn how to input data from the user save data into the file and then read data from the file and print it?
Submitted by Pankaj Singh, on December 30, 2018
Here, we have to input the data from the user, to read the data from user, we use input() method, and then the input data we have to store in the file by using write() method and then by using read() method we can get the data.
Here is the python code to save and read the data:
def main():
# open file in write mode
fo = open("data2.txt","wt")
# Input the user data
data = input("Enter Some Data to Save: ")
# write data to the file
fo.write(data)
# close the file
fo.close()
# open file again in read mode
fo = open("data2.txt","rt")
# read the data from the file
str=fo.read()
# print the read data
print("\nThe Content of File is:")
print(str)
# close the file
fo.close()
if __name__=="__main__":main()
Output
Enter Some Data to Save: Hello friends, how are you?
The Content of File is:
Hello friends, how are you?