βοΈ Python Write/Create Files β write(), writelines(), Modes Explained
π§² Introduction β Why Learn File Writing in Python?
Writing to files is a vital part of real-world programming. Whether you’re logging data, exporting reports, or generating configuration files, Python’s built-in functions make file creation and manipulation seamless and powerful.
π― In this tutorial, you’ll learn:
- How to create and write to files in Python
- File modes like
w
,a
, andx
- Writing strings vs writing lists
- Appending vs overwriting data
- Best practices for efficient file handling
π 1. Create or Write to a File using open()
β Syntax:
file = open("output.txt", "w")
file.write("This is a new file.")
file.close()
β This creates a new file if it doesn’t exist, or overwrites if it does.
π Best Practice β Use with
Statement
with open("output.txt", "w") as file:
file.write("Hello, Python File Writer!")
β
Why use with
?
- Automatically closes the file
- Cleaner and safer code
βοΈ 2. Python File Write Modes Explained
Mode | Description |
---|---|
'w' | Write (overwrite file if exists) |
'a' | Append (add to end of file) |
'x' | Create (fail if file already exists) |
'w+' | Write + Read |
'a+' | Append + Read |
'b' | Binary mode (e.g., 'wb' ) |
't' | Text mode (default) |
π§Ύ 3. Writing with write()
β Single String
with open("log.txt", "w") as f:
f.write("Log Entry 1\n")
f.write("Log Entry 2\n")
β Writes string data to file.
β οΈ Warning: This overwrites the file every time it’s opened in 'w'
mode.
π 4. Writing with writelines()
β List of Strings
lines = ["First Line\n", "Second Line\n", "Third Line\n"]
with open("data.txt", "w") as f:
f.writelines(lines)
β Best for multiple lines stored in a list.
π‘ Tip: Make sure each string ends with \n
.
β 5. Appending to a File β a
Mode
with open("data.txt", "a") as f:
f.write("Appended line\n")
β Adds content at the end without erasing existing data.
π« 6. Creating a New File β x
Mode
with open("newfile.txt", "x") as f:
f.write("This file is created only if it doesn't exist.")
β Fails if file already exists.
π‘ Tip: Use it to avoid overwriting by mistake.
π‘ 7. Writing Variables and Loops
names = ["Alice", "Bob", "Charlie"]
with open("names.txt", "w") as f:
for name in names:
f.write(name + "\n")
β Simple way to write lists with formatting.
π§ͺ 8. Real-World Example: Save User Input to File
name = input("Enter your name: ")
with open("users.txt", "a") as f:
f.write(name + "\n")
β Appends user entries into a file like a guestbook.
β οΈ 9. Common Mistakes to Avoid
β Forgetting to close file (fixed by using with
)
β Using w
when you meant to append with a
β Writing lists directly without joining strings
β Use:
f.write("\n".join(mylist))
π Summary β Recap & Next Steps
Pythonβs open()
function combined with write()
, writelines()
, and file modes like w
, a
, and x
allows flexible, efficient file output. Use the with
statement to avoid manual resource handling.
π Key Takeaways:
- Use
'w'
to overwrite,'a'
to append,'x'
to create new files - Use
write()
for strings andwritelines()
for lists - Always prefer
with open()
for safety - Use loops or
join()
to handle lists or dynamic data
βοΈ Real-World Relevance:
Used in logging, data export, report generation, user input storage, and more.
β FAQ β Python Write/Create Files
β How do I create a file only if it doesn’t exist?
β Use:
open("file.txt", "x")
Raises FileExistsError
if file already exists.
β What’s the difference between write()
and writelines()
?
write()
β Writes a single stringwritelines()
β Writes a list of strings
β How do I prevent overwriting files?
β
Use 'a'
mode to append
β
Or 'x'
mode to create file only if it doesn’t exist
β Can I write and read from the same file?
β
Yes, use 'w+'
or 'a+'
mode:
with open("file.txt", "w+") as f:
f.write("test")
f.seek(0)
print(f.read())
β Do I need to add \n
manually?
β
Yes. Python does not add newlines automatically with write()
or writelines()
.
Share Now :