-
Hajipur, Bihar, 844101
Writing and creating files in Python allows your programs to store data permanently, which can later be accessed, modified, or shared. Python provides simple built-in functions for writing and creating files in both text and binary formats. Mastering this topic is essential for data storage, logging, and automation tasks.
This tutorial covers writing to files, creating new files, appending data, handling file modes, and practical examples.
To write or create a file, Python uses the open() function with specific file modes:
file = open("example.txt", "w") # Open file in write mode
'w' – Write mode (creates a new file or overwrites existing one)
'x' – Create mode (creates a new file, throws an error if it exists)
'a' – Append mode (adds content to the end of an existing file)
After writing, you must close the file to save changes:
file.close()
Using a context manager is recommended:
with open("example.txt", "w") as file:
file.write("Hello, Python!\n")
The write() method writes a string to a file:
with open("example.txt", "w") as file:
file.write("Python File Handling Tutorial\n")
file.write("This is a new file.\n")
Key points:
write() accepts a single string
You must include \n for new lines manually
writelines()If you have a list of strings, writelines() can write all lines at once:
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("example.txt", "w") as file:
file.writelines(lines)
writelines() does not automatically add newlines, so include \n at the end of each string.
Python allows creating new files using w or x mode:
w Mode:with open("newfile.txt", "w") as file:
file.write("This is a newly created file using 'w' mode.\n")
If the file already exists, its content will be overwritten.
x Mode:with open("newfile2.txt", "x") as file:
file.write("This file is created using 'x' mode.\n")
x mode throws an error if the file already exists, which prevents accidental overwriting.
To add content without deleting existing data, use append mode 'a':
with open("example.txt", "a") as file:
file.write("This line will be added to the file.\n")
Append mode is ideal for logs, sequential records, and incremental updates.
For non-text files like images or PDFs, use binary write mode 'wb':
data = b"This is binary data."
with open("example.bin", "wb") as file:
file.write(data)
Binary files store bytes instead of text and are used for images, audio, and other binary formats.
The with statement automatically closes the file after operations, even if an error occurs:
with open("example.txt", "w") as file:
file.write("This file is safely written using context manager.\n")
This approach prevents data loss and resource leaks.
Write a single line to a file:
with open("example.txt", "w") as file:
file.write("Hello, Python File Handling!\n")
Write multiple lines using writelines():
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("example.txt", "w") as file:
file.writelines(lines)
Create a new file using 'x' mode:
with open("newfile.txt", "x") as file:
file.write("New file created.\n")
Append text to an existing file:
with open("example.txt", "a") as file:
file.write("Appending a new line.\n")
Write a list of names to a file:
names = ["Ananya\n", "Meera\n", "Riya\n"]
with open("students.txt", "w") as file:
file.writelines(names)
Write formatted text using a loop:
with open("numbers.txt", "w") as file:
for i in range(1, 6):
file.write(f"Number {i}\n")
Write binary data to a file:
data = b"Binary data example."
with open("data.bin", "wb") as file:
file.write(data)
Write user input to a file:
user_input = input("Enter some text: ")
with open("user.txt", "w") as file:
file.write(user_input + "\n")
Write CSV-like data to a text file:
data = ["Name,Age\n", "Ananya,22\n", "Meera,20\n"]
with open("data.txt", "w") as file:
file.writelines(data)
Append multiple lines from a list:
new_lines = ["Sana\n", "Muskan\n"]
with open("students.txt", "a") as file:
file.writelines(new_lines)
Writing and creating files in Python is essential for data persistence and automation. The key points are:
Use 'w' mode to write or overwrite files
Use 'x' mode to create new files safely
Use 'a' mode to append data without overwriting
Use write() for single strings and writelines() for lists of strings
Use binary modes for non-text files
Always use context managers (with) for safe file handling
Mastering file writing and creation enables you to store program output, maintain logs, and manage data efficiently, which is crucial for real-world Python applications.
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.