Nearby lessons

91 of 159

Python - Create Files

📌 What You Will Learn
  • Create a new file using the exclusive creation mode x
  • Understand why x raises FileExistsError when the file exists
  • Compare the x mode with the w mode for creating files
  • Inspect a newly created file using file object properties
  • Close a file after creating it

Creating a New File

In Python, we create a new file by opening it in write mode (w) or exclusive creation mode (x).

Both modes create the file if it does not already exist.

The Exclusive Creation Mode (x)

The x mode is used to create a new file exclusively.

If the file already exists, Python raises FileExistsError instead of overwriting it.

Syntax

Loading editor…

Example: Create a New File

Loading editor…

Example: FileAlready Exists

If we run the same program a second time, newfile.txt already exists.

Loading editor…

Explanation

The first run creates newfile.txt successfully.

The second run fails because the file already exists. The x mode intentionally prevents two parts of a program from accidentally creating the same file.

x Mode vs w Mode

x Mode w Mode
Creates a new file. Creates a new file.
Raises FileExistsError if the file already exists. Overwrites the existing file silently.
Safe for creating a file that must not be overwritten. Used when the file content should start fresh.

Inspecting a Newly Created File

After creating a file, we can inspect the file object to confirm its name, mode, and capabilities.

Loading editor…

Explanation

  • f.name returns abc.txt.
  • f.mode returns x.
  • f.readable() returns False because exclusive creation does not support reading.
  • f.writable() returns True because the file is created for writing.
  • f.closed returns False before close() and True after it.
📝 Key Takeaways
  • The x mode creates a brand-new file and raises FileExistsError if it already exists
  • x mode prevents accidentally overwriting an existing file
  • w mode also creates a file but overwrites existing data instead
  • open() returns a file object that exposes name, mode, readable(), writable(), and closed
  • Always close a file after creation to release its resources

🧠 Test Your Knowledge

6 Questions
Progress: 0 / 6

Finished this lesson?

Mark it as complete to track your progress and see technology completion stats.