Python Tutorials · File Handling

Python Write/Create Files

Learn all about Python Write/Create Files in this comprehensive tutorial.

5 min read intermediate
  • To write to an existing file, you must add a parameter to the open() function:
  • To overwrite the existing content to the file, use the w parameter:
  • To create a new file in Python, use the open() method, with one of the following parameters:

Write to an Existing File

To write to an existing file, you must add a parameter to the open() function:

"a" - Append - will append to the end of the file

"w" - Write - will overwrite any existing content

python

Overwrite Existing Content

To overwrite the existing content to the file, use the w parameter:

python
Note: Note: the "w" method will overwrite the entire file.

Create a New File

To create a new file in Python, use the open() method, with one of the following parameters:

"x" - Create - will create a file, returns an error if the file exists

"a" - Append - will create a file if the specified file does not exists

"w" - Write - will create a file if the specified file does not exists

python

Result: a new empty file is created.

Note: Note: If the file already exists, an error will be raised.

Module quiz

2 questions
1

Which of the following is true about Python Write/Create Files?

2

What is the most common pitfall when working with Python Write/Create Files?

Answer all questions to submit.