Python Write File


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

The string content is stored in the buffer until the file is closed or until the buffer is refreshed, at which point you won't see what is written in the file.

If the file is opened in b mode, then when writing the contents of the file, str (argument) must be converted to bytes using the encode method, otherwise an err

Related course: Complete Python Programming Course & Exercises

Syntax

The syntax of the write() method is as follows.

fileObject.write( [ str ])

Parameters

  • str -- the string to write to the file.

Return value.

What is returned is the length of the characters written.

Python Write File using write() function

The most basic example is only a few lines of code:

tfile = open("readme.txt", "a")
# with open("readme.txt") as tfile:   # close automatically, alternative
tfile.write("123 hello")
tfile.close()

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

#!/usr/bin/python
#-*- coding: UTF-8 -*-

# open file
fo = open("test.txt", "w")
print("File name is: ", fo.name)

# write file
str = "python tutorial"
fo.write( str )

# close file
fo.close()

The output of the above example is.

The file name is: test.txt

View the contents of the document.

$ cat test.txt
python tutorial

Using writelines() in Python

You can write a Python list to a file like this:

>>> f=open(r"test.txt",'w')
>>> f.writelines(['love','python','love python'])
>>> f.close()

If you have a string with newline characters, you can use it too:

>>> f=open(r"test.txt",'w')
>>> f.writelines('love\npython\nlove python\n')
>>> f.close()

Each line is writen in a new line. But not without newline characters,

>>> f=open(r"test.txt",'w')
>>> f.writelines('lovepythonlove python')
>>> f.close()