Writing Data to a File :
The write( ) method writes a string to the file. If the data is already present, the new data is overwritten on the old data.
Python
file = open("data.txt", "w") file.write("Hello Python") file.close() Writing a List of Lines :
The writelines( ) method writes multiple lines at once.
Python
lines = ["Python\n", "Java\n", "C++\n"] file = open("languages.txt", "w") file.writelines(lines) file.close() | Mode | Behavior |
|---|---|
w | Overwrites file |
a | Adds data to end |