Python - File write() Method


Advertisements

The Python file write() method is used to write content in the specified open file.

Syntax


file.write(byte)

Parameters

byte Optional. specify text or byte object which need to be inserted.

Write to an Existing File

To write content in the existing file, two file open() modes can be used.

  • "a" - append mode. to append to the end of the file.
  • "w" - write mode. to overwrite any existing content of the file.

The below example explains how to write content in a given file in append and write mode.

#append content to the file 
MyFile = open("python_test.txt", "a")
MyFile.write("add more content.")
MyFile.close()

#overwrite existing content of the file 
MyFile = open("python_test.txt", "w")
MyFile.write("add more content.")
MyFile.close()

Create a New File

To create a new file, the file open() function can be used in following modes:

  • "a" - append mode. Opens a file in append mode and creates the file if it does not exist.
  • "w" - write mode. Opens a file in write mode and creates the file if it does not exist.
  • "x" - create mode. Creates a file and raises exception if it already exists.

The below example explains how to create a new file called NewFile if it does not exist using append, write and create mode.

#Creates a file "MyFile" if it does not exist 
MyFile = open("python_test.txt", "a")
MyFile.write("Add content.")
MyFile.close()

#Creates a file "MyFile" if it does not exist 
MyFile = open("python_test.txt", "w")
MyFile.write("Add content.")
MyFile.close()

#Creates a file "MyFile" if it does not exist  
MyFile = open("python_test.txt", "x")
MyFile.write("Add content.")
MyFile.close()

Python File Handling Methods
Advertisements