In Python, you can write to files using two main modes: wa
Mode w (Write mode):
When you open a file in write mode w
This means if the file already has some text, it will delete everything and start fresh.
Mode a (Append mode):
When you open a file in append mode a
This is useful when you want to add new data to an existing file without overwriting it.
Writing methods
.write()
Example:
with open("example.txt", "w") as file:
file.write("Hello, World!\n")
file.write("This is a new line.")
In this case, "Hello, World!" and "This is a new line." will be written to the file example.txt.
The .write()
It doesn’t add a newline automatically after the string, so you need to manually include \n if you want to start a new line.
.writelines():
Example:
lines = ["First line\n", "Second line\n", "Third line\n"]
with open("example.txt", "w") as file:
file.writelines(lines)
This will write the lines "First line", "Second line", and "Third line" to the file, each on a new line.
- The
method is used to write a list of strings to a file..writelines() - Unlike
, it doesn’t automatically add newlines, so each string in the list should have a newline (.write()\n) if needed.
Difference between w and a
-
(write): If you open a file in write modew , it will overwrite any existing content in the file. This is like starting with a clean slate.w -
(append): If you open a file in append modea , it will add new content to the end of the file without affecting the current content.a
Example to illustrate:
Using w mode (overwrite):
with open("test.txt", "w") as file:
file.write("This is the first line.")
If test.txt already had some content, it will now only contain "This is the first line."
Using a mode (append):
with open("test.txt", "a") as file:
file.write("\nThis is an added line.")
After this, the file test.txt will contain:
This is the first line.
This is an added line.
