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?





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.