Writing text to a file using 'with' - Python Context Manager - Hands On

Python Python Classes and Objects (Article) Python Classes and Objects (Program)

307

1. Writing text to a file using 'with'

• Define a function 'writeTo' with two parameters, 'filename' and 'text'. 'text' takes any input string, and 'filename' refers to the name of the file in which the input text is written.

Hint: Use 'with' to open the file in which the input text is written.

Given Input:

sample.txt
python is awesome

Expected Output:

'with' used in 'writeTo' function definition.
File : sample.txt is present on system.
File Contents are : python is awesome

Program:

#!/bin/python3

import sys
import os
import inspect

# Complete the function below.

def writeTo(filename, input_text):

    with open(filename, "w") as f:

        f.write(input_text)


if __name__ == "__main__":
    try:
        filename = str(input())
    except:
        filename = None

    try:
        input_text = str(input())
    except:
        input_text = None

    res = writeTo(filename, input_text)
    
    if 'with' in inspect.getsource(writeTo):
        print("'with' used in 'writeTo' function definition.")
        
    if os.path.exists(filename):
        print('File :',filename, 'is present on system.')
        with open(filename) as fp:
            content = fp.read()
        if content == input_text:
            print('File Contents are :', content)
    

Output:

'with' used in 'writeTo' function definition.
File : sample.txt is present on system.
File Contents are : python is awesome

This Particular section is dedicated to Programs only. If you want learn more about Python. Then you can visit below links to get more depth on this subject.