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

🐍Code Cell
1f = open(filename, "x")
Output
No output captured.

Example: Create a New File

🐍Code Cell
1f = open("newfile.txt", "x")
2 
3print("newfile.txt created successfully")
4 
5f.close()
Output
newfile.txt created successfully

Example: FileAlready Exists

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

🐍Code Cell
1f = open("newfile.txt", "x")
2 
3print("newfile.txt created successfully")
4 
5f.close()
Output
FileExistsError: [Errno 17] File exists: 'newfile.txt'

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.

🐍Code Cell
1f = open("abc.txt", "x")
2 
3print("File Name: ", f.name)
4print("File Mode: ", f.mode)
5print("Is File Readable: ", f.readable())
6print("Is File Writable: ", f.writable())
7print("Is File Closed : ", f.closed)
8 
9f.close()
10 
11print("Is File Closed : ", f.closed)
Output
File Name: abc.txt
File Mode: x
Is File Readable: False
Is File Writable: True
Is File Closed : False
Is File Closed : True

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