← Back to Chapters

Python Write & Create Files

? Python Write & Create Files

? Quick Overview

Python allows you to create, write, and append to files so that data can be stored permanently on disk. Using different file modes ("w", "a", "x") you can control whether a file is created, overwritten, or extended with new content.

? Key Concepts

  • File modes: "w" (write), "a" (append), "x" (create).
  • Context manager (with): automatically opens and safely closes the file.
  • write(): writes a single string to the file.
  • writelines(): writes multiple strings from a list to the file.
  • Newline characters (\n): used to move to a new line in the file.

? Syntax & File Modes

? Common modes

  • "w" – Create a new file or overwrite if it already exists.
  • "a" – Append data at the end of an existing file (create if not present).
  • "x" – Create a new file; raises an error if the file already exists.

⚙️ Basic syntax

  • open(filename, mode) returns a file object.
  • Using with open(...) as f: ensures the file is closed automatically.
  • Always include \n when you want text on a new line in the file.

? Code Examples

⚡ Write to a New File (overwrite if it exists)

? View Code Example
# Open a new file in write mode (overwrites if it exists)
with open("newfile.txt", "w") as file:
    # Write the first line with a newline character
    file.write("Hello, World!\n")
    # Write the second line without adding an extra newline
    file.write("This is a new file.")

? Append to an Existing File

? View Code Example
# Open the file in append mode to add new content at the end
with open("newfile.txt", "a") as file:
    # Add a new line to the existing file content
    file.write("\nAppending a new line.")

? Create a File Only if it Does Not Exist

? View Code Example
# Create a new file only if it does not already exist
file = open("anotherfile.txt", "x") # Raises FileExistsError if file already exists
# Close the file after creating it
file.close()

? Write Multiple Lines with writelines()

Use writelines() to write a list of strings to a file in one go.

? View Code Example
# Prepare a list of lines, each ending with a newline character
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
# Open the file in write mode and write all lines at once
with open("newfile.txt", "w") as file:
    # Write each string from the list into the file
    file.writelines(lines)

? Output & Explanation

? What will the file contain?

After the first example ("w" mode), the file newfile.txt will contain:

Hello, World!
This is a new file.

After the append example ("a" mode), the same file will contain:

Hello, World!
This is a new file.
Appending a new line.

Using "x" creates a new file only if it does not already exist. If you run the code again and anotherfile.txt is already present, Python will raise a FileExistsError.

? Tips & Best Practices

  • Prefer using the with statement so files are closed automatically, even if an error occurs.
  • Use "a" mode when you want to add content without removing existing data.
  • Include \n at the end of each line when using write() or writelines().
  • Use writelines() when you already have data as a list of strings.
  • Be careful with "w" mode — it will overwrite the file completely.

? Try It Yourself

  • Create a file called quotes.txt and write your favorite quotes, one per line.
  • Append two more quotes to quotes.txt without removing the existing content.
  • Create a list of numbers (as strings with \n) from 1 to 10 and write them to numbers.txt using writelines().
  • Experiment with "x" mode and observe what happens when the file already exists.