In this Python example, I am going to create a Python program that will get the user poet inputs and then save them inside a file, and after that displayed those poets back on the screen.
I am going to use the open-file method together with the (with) keyword which will close the file after the write and the read methods have completed their duty.
If the file has not been created yet then the open method will create it, and the user inputs will get appended at the back of the existing contents inside the same file. The open method also will use UTF-8 as its encoding system.
The user input method will get the user poet’s inputs and the write method will write the poet into the file, in order to insert a new line after each poet, the ‘\n’ has been inserted at the back of each poet entry.
The for loop will be used to ask the user to enter three poets into the file (if you are interested to learn the for loop of another programming language then do visit this post).
At last those poets have been printed on the screen again with the help of the file’s write method!
for count in range(0,3): # receive input of three poets poet = input("Enter your " + str(count+1) + " poet : ") with open("poet.txt",'a',encoding = 'utf-8') as f: f.write(poet+"\n") # put each poet in a new line with open("poet.txt") as f: print(f.read()) # write out all three poets in the file
*The range method will generate the number from 0 to 2 thus I will need to add 1 to the count on each loop cycle!
The outcome is as follows:-
Enter your 1 poet : I am a middle age man who has no planned Enter your 2 poet : and no girlfriend Enter your 3 poet : I live inside a homeless tent and continue to write my Python program I am a middle age man who has no planned and no girlfriend I live inside a homeless tent and continue to write my Python program