w3resource

Python File I/O: Append text to a file and display the text


3. Append Text and Display

Write a Python program to append text to a file and display the text.

Sample Solution:-

Python Code:

def file_read(fname):
        from itertools import islice
        with open(fname, "w") as myfile:
                myfile.write("Python Exercises\n")
                myfile.write("Java Exercises")
        txt = open(fname)
        print(txt.read())
file_read('abc.txt')

Sample Output:

Python Exercises                                                                                              
Java Exercises 

Flowchart:

Flowchart: File I/O:  Append text to a file and display the text.

For more Practice: Solve these Related Problems:

  • Write a Python program to append a given string to a file and then read and display the updated contents.
  • Write a Python program to append text to a file only if that text does not already exist in the file, then display the file.
  • Write a Python program to append multiple lines from a list to a file and then print the last few lines to confirm the append.
  • Write a Python program to append the current timestamp to a file each time it is modified and then display the file's content.

Go to:


Previous: Write a Python program to read first n lines of a file.
Next: Write a Python program to read last n lines of a file.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.