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
3 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
When and why should you suppress the EOL translation in csv file handling ?
If you rename a text file's extension as .csv, will it become a csv file ? Why/why not ?
Differentiate between the following :
(i) f = open('diary.txt', 'r')
(ii) f = open('diary.txt', 'w')
How are following codes different from one another ?
(a)
my_file = open('poem.txt', 'r') my_file.read()
(b)
my_file = open('poem.txt', 'r') my_file.read(100)