📂 Python File Handling
Estimated reading: 4 minutes 297 views

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, and x
  • 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

ModeDescription
'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 and writelines() 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 string
  • writelines() → 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 :
Share

Python Write/Create Files

Or Copy Link

CONTENTS
Scroll to Top