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
Test your knowledge on this module
5 questions