Python Program to Read a String from the User and Append it into a File

This is a Python Program to read a string from the user and appends it into a file

Problem Description

The program takes a string from the user and appends the string into an existing file.

Problem Solution

1. Take the file name from the user.
2. Open the file in append mode.
2. Take in a string from the user, append it to the existing file and close the file.
3. Open the file again in read mode and display the contents of the file.
4. Exit.

Program/Source Code

Here is source code of the Python Program to read a string from the user and appends it into a file. The program output is also shown below.

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()
Program Explanation

1. User must enter a file name.
2. The file is opened using the open() function in the append mode.
3. A string is taken from the user, appended to the existing file and is closed.
4. The file is opened again in the read mode.
5. The readline() in the while loop reads each and every line in the file and print() prints the contents on the output screen.

advertisement
advertisement
Runtime Test Cases
 
Case 1:
Contents of file: 
Hello world
 
Output: 
Enter file name: test.txt
Enter string to append: 
test
Contents of appended file:
Hello world
 
test
 
Case 2:
Contents of file: 
This programming language is
Python
 
Output: 
Enter file name: test1.txt
Enter string to append: 
test
Contents of appended file:
This programming language is
Python
 
test

Sanfoundry Global Education & Learning Series – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.