Writing text to a file using 'with' - Python Context Manager - Hands On
Writing text to a file using 'with' - Python Context Manager - Hands On
Writing text to a file using 'with' - Python Context Manager - Hands On
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.
sample.txt python is awesome
'with' used in 'writeTo' function definition. File : sample.txt is present on system. File Contents are : python is awesome
#!/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)
<pre class="prettyprint">
'with' used in 'writeTo' function definition.
File : sample.txt is present on system.
File Contents are : python is awesome
</pre>
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.
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.