This is a Python Program to read a string from the user and appends it into a file
The program takes a string from the user and appends the string into an existing file.
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.
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()
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.
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.
- Practice Programming MCQs
- Apply for Python Internship
- Apply for Programming Internship
- Check Information Technology Books
- Check Python Books