-
Hajipur, Bihar, 844101
In Python, you can create and write to files using the open()
function with the modes "w"
, "a"
, or "x"
.
w
– Write (Overwrite)f = open("demo.txt", "w")
f.write("This is a new line.")
f.close()
✅ If the file doesn't exist, it will be created.
⚠️ If it exists, it will overwrite everything.
a
– Append (Add at End)f = open("demo.txt", "a")
f.write("\nAnother line added.")
f.close()
✅ Adds content to the end without deleting existing data.
x
– Create (Error if File Exists)f = open("newfile.txt", "x")
f.write("File created using x mode.")
f.close()
❌ Raises an error if the file already exists.
f = open("demo.txt", "w")
f.writelines(["Line 1\n", "Line 2\n", "Line 3\n"])
f.close()
✅ writelines()
takes a list of strings.
with open("binaryfile.bin", "wb") as f:
f.write(b"This is binary data.")
with
with open("demo.txt", "w") as f:
f.write("Safe writing using with.")
✅ File automatically closes after use.
import os
if not os.path.exists("demo.txt"):
f = open("demo.txt", "w")
f.write("File created safely.")
f.close()
Q1. Write a Python program to write "Hello World"
to a file using "w"
mode.
Q2. Write a Python program to create a file only if it doesn’t exist using "x"
mode.
Q3. Write a Python program to append a new line to notes.txt
using "a"
mode.
Q4. Write a Python program to overwrite the contents of log.txt
with a new message using "w"
mode.
Q5. Write a Python program to write multiple lines to a file using the writelines()
method.
Q6. Write a Python program to write a binary string to a .bin
file using "wb"
mode.
Q7. Write a Python program to use with open()
to write to a file safely and automatically close it.
Q8. Write a Python program to check if a file exists before writing to it using "w"
mode, using os.path.exists()
.
Q9. Write a Python program to create a function that takes user input and saves it to a file.
Q10. Write a Python program to append today’s date to a file, using the datetime
module.
Q1: What does "w" mode do in open()?
Q2: What happens if the file exists and you open it in "w" mode?
Q3: Which mode is used to create a file only if it does not exist?
Q4: What does writelines() accept?
Q5: What mode should be used to append data?
Q6: What does "wb" mode mean?
Q7: What is the purpose of with open()?
Q8: What does open("file.txt", "x") do if file exists?
Q9: Which function writes text to a file?
Q10: How to write multiple lines at once?