KnowledgeBoat Logo
|

Computer Science

Differentiate between "w" and "r" file modes used in Python while opening a data file. Illustrate the difference using suitable examples.

Python File Handling

12 Likes

Answer

"w" mode"r" mode
It is also called as write mode.It is also called as read mode.
The "w" mode is used to open a file for writing.The "r" mode is used to open a file for reading.
It creates a new file if the file does not exist.If the file does not exist, it raises a FileNotFoundError.
If the file exists, Python will truncate existing data and over-write in the file.If the file exists, Python will open it for reading and allow to access its contents.
Example:
with open("example.txt", "w") as file:
file.write("Hello, world!\n")
Example:
with open("example.txt", "r") as file:
data = file.read()
print(data)

Answered By

2 Likes


Related Questions