Home / Programs / Writing text to a file using 'with' - Python Context Manager - Hands On
🚀 Programming Example

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

👁 396 Views
💻 Practical Program
📘 Step Learning

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

📌 Information & Algorithm

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 Code

#!/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)
    


                        

🖥 Program Output

<pre class="prettyprint">
'with' used in 'writeTo' function definition.
File : sample.txt is present on system.
File Contents are : python is awesome
</pre>
                            
📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.