Write a program to read a String from the User and Append it into a File in Python
In this tutorial we are going to learn about reading a String from the User and Append it into a File in Python.
fname = input("Enter file name: ") file3=open(fname,"a") c=input("Enter string to append: \n"); file3.write("\n") file3.write(c) file3.close() print("Contents of appended file:"); file4=open(fname,'r') line1=file4.readline() while(line1!=""): print(line1) line1=file4.readline() file4.close()
- User must enter a file name.
- The file is opened using the open() function in the append mode.
- A string is taken from the user, appended to the existing file and is closed.
- The file is opened again in the read mode.
- The readline() in the while loop reads each and every line in the file and print() prints the contents on the output screen.