9-3. Creating a New File in Python

In Python, you can create a new file using the open() function with specific modes. Here’s how you can do it with different modes:

  • Create Mode ("x"): Creates a new file and returns an error if the file already exists.
  • Append Mode ("a"): Opens a file for appending and creates the file if it does not exist.
  • Write Mode ("w"): Opens a file for writing and creates the file if it does not exist.

Example: Creating a File Using Write Mode

To create a file using the write mode, which will create the file if it does not exist:

Explanation:

  • Open the File in Write Mode: Use open("newfile_write.txt", "w") to open the file for writing. This will create the file if it does not exist.
  • Write to the File: Use write() to add content to the file.
  • Close the File: Always close the file after performing operations on it.
  • Read the File: Reopen the file in read mode to verify its content.

This code example demonstrates creating a file of usernames from a file that contains names.