Nearby lessons
91 of 159Python - 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
Example: Create a New File
Example: FileAlready Exists
If we run the same program a second time, newfile.txt already exists.
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.
Explanation
f.namereturnsabc.txt.f.modereturnsx.f.readable()returnsFalsebecause exclusive creation does not support reading.f.writable()returnsTruebecause the file is created for writing.f.closedreturnsFalsebeforeclose()andTrueafter 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 QuestionsProgress: 0 / 6