Foundations of Python

104 / 134

Writing Files

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 write mode.

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 'w' to '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 'a',

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

INSTRUCTIONS
  • Open a file python_file_writing.txt in write mode
  • Write content to the file I am learning Python at CloudxLab.
  • Execute the code and submit the answer

Note: Use the exact file name and content as above, for correct answer. Also check the path using !pwd, it should return /home/*your_username*/cloudxlab_jupyter_notebooks .



Note - Having trouble with the assessment engine? Follow the steps listed here

Loading comments...