Flash Sale: Flat 70% + Addl. 25% Off on all Courses | Use Coupon DS25 in Checkout | Offer Expires InEnroll Now
Till now we were opening the file in
read mode, but we can also open the file in
write mode if we have the permission to make changes or edit the file.
We need to mention
'w' as an argument if we want to open a file in the
Try opening our sample file in
write mode and see the result,
with open("/cxldata/python_sample_file", 'w') as f: print(f.read())
You will get an error saying, "Permission denied: ..." because you don't have permission to write files in
/cxldata directory. Alternately, while opening the file in
read mode, you can mention
'r' as an argument (but not necessary).
Now, change the
'r' in the above code and see the result.
On opening a file in
'w' mode all changes that we make completely replace the content present earlier in the file.
Suppose there is a file
cxl.txt in the current folder that contains
"cloudxlab" as the only word inside it and provided you have the permission to edit it,
with open("cxl.txt", 'w') as f: f.write("Python is a scripting language")
write function writes the argument passed in the brackets to the file and replaces the original content of the file. To avoid replacing the original content in the file, we have another mode for opening the file call append, written as
with open("cxl.txt", 'a') as f: f.write("Python is a scripting language")
Now, if you try reading the content of the file, it will have
Python is a scripting language
python_file_writing.txtin write mode
I am learning Python at CloudxLab.
Note: Use the exact file name and content as above, for correct answer. Also check the path using !pwd, it should return
No hints are availble for this assesment
Answer is not availble for this assesment
Note - Having trouble with the assessment engine? Follow the steps listed here