Python Tutorial Python Advanced Python References Python Libraries

Python - File write() Method



The Python 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.

Return Value

None.

Write to an Existing File

To write content in the existing file, the following 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 code can be used to write content to a given file using append and write mode respectively.

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

#overwrite existing content of the file 
MyFile = open("test.txt", "w")
MyFile.write("Overwrite content.")
MyFile.close()

Write to 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 code can be used to create a new file called test.txt (if the file does not exit) using append, write and create mode respectively.

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

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

#Creates a new file "test.txt" and raises
#exception if it already exists
MyFile = open("test.txt", "x")
MyFile.write("Add content.")
MyFile.close()

Example:

In the example below, the file write() method is used to write content to a new file.

#file is opened in write mode
MyFile = open("test.txt", "w")
MyFile.write("Hello World!")
MyFile.close()

#read the file
MyFile = open("test.txt", "r")
print(MyFile.read())
MyFile.close()

The output of the above code will be:

Hello World!

❮ Python File Handling Methods

5