Easy Tutorial
❮ Ref Math Cosh Python Comprehensions ❯

Python3 File write() Method

Python3 File Methods


Overview

The write() method is used to write a specified string to a file.

Before the file is closed or the buffer is flushed, the string content is stored in the buffer, and you won't see the written content in the file.

If the file opening mode includes 'b', the string (parameter) must be converted to bytes format using the encode method; otherwise, an error will occur: TypeError: a bytes-like object is required, not 'str'.

Syntax

The syntax for the write() method is as follows:

fileObject.write( [ str ])

Parameters

Return Value

The method returns the length of the written string.

Example

The content of the file tutorialpro.txt is as follows:

1:www.tutorialpro.org
2:www.tutorialpro.org
3:www.tutorialpro.org
4:www.tutorialpro.org
5:www.tutorialpro.org

The following example demonstrates the use of the write() method:

#!/usr/bin/python3

# Open the file
fo = open("tutorialpro.txt", "r+")
print("File name: ", fo.name)

str = "6:www.tutorialpro.org"
# Write a line at the end of the file
fo.seek(0, 2)
line = fo.write(str)

# Read the entire file content
fo.seek(0,0)
for index in range(6):
    line = next(fo)
    print("File line number %d - %s" % (index, line))

# Close the file
fo.close()

The output of the above example is:

File line number 0 - 1:www.tutorialpro.org
File line number 1 - 2:www.tutorialpro.org
File line number 2 - 3:www.tutorialpro.org
File line number 3 - 4:www.tutorialpro.org
File line number 4 - 5:www.tutorialpro.org
File line number 5 - 6:www.tutorialpro.org

View the file content:

$ cat tutorialpro.txt 
1:www.tutorialpro.org
2:www.tutorialpro.org
3:www.tutorialpro.org
4:www.tutorialpro.org
5:www.tutorialpro.org
6:www.tutorialpro.org

Python3 File Methods

❮ Ref Math Cosh Python Comprehensions ❯