The Anubhav portal was launched in March 2015 at the behest of the Hon'ble Prime Minister for retiring government officials to leave a record of their experiences while in Govt service .
In Python, writing to a file is simple using the built-in open() function. Here’s a quick guide with examples for writing, appending, and creating files.
1. Write to a File (Overwrite Mode)
# This will create a file if it doesn't exist or overwrite it if it does
with open("example.txt", "w") as file:
file.write("Hello, world!\n")
file.write("This is a new line.")
"w" → write mode
It overwrites the file if it already exists.
2. Append to a File (Add New Content)
# This will create the file if it doesn't exist, or append if it does
with open("example.txt", "a") as file:
file.write("\nThis line will be appended.")
"a" → append mode
It adds new content without removing old data.
3. Read and Write (Combined Mode)
# Opens the file for both reading and writing
with open("example.txt", "r+") as file:
data = file.read()
file.write("\nAdded after reading content.")
"r+" → read and write mode
File must already exist.
4. Write Multiple Lines at Once
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("example.txt", "w") as file:
file.writelines(lines)
writelines() doesn’t add \n automatically — include it in each string.
5. Create a File Only If It Doesn’t Exist
try:
with open("example.txt", "x") as file:
file.write("New file created.")
except FileExistsError:
print("File already exists.")
"x" → exclusive creation mode.
Join MindStick Community
You need to log in or register to vote on answers or questions.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
1. Write to a File (Overwrite Mode)
"w"→ write mode2. Append to a File (Add New Content)
"a"→ append mode3. Read and Write (Combined Mode)
"r+"→ read and write mode4. Write Multiple Lines at Once
writelines()doesn’t add\nautomatically — include it in each string.5. Create a File Only If It Doesn’t Exist
"x"→ exclusive creation mode.