The write() method needs a previously-opened file object and some argument, usually a string (but could be a bytes type). In some ways, each write() is like a print statement or print() function (in Python 3). However, unlike print, the write() method does not automatically add a newline character: each write() occurrence just appends to what has been written before. To emphasize this, the following two functions blockwrite and charwrite do exactly the same thing.

1
2
3
4
5
def blockwrite(fileobject,stringarg):
    fileobject.write(stringarg)
def charwrite(fileobject,stringarg):
    for char in stringarg:
        fileobject.write(char) 

Furthermore, individual write() calls can be separated in time and place within the program, and have the same result as if they had been done all at once.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
def itemwrite(fileobject,itemlist):
    for item in itemlist:
        fileobject.write(item)
F = open("testing.txt",'w')
S = '''Replaced my shoelaces 
with ear buds 
and now they tie themselves.'''
words = S.split()
F.write(words[0])
del words[0]
itemwrite(F,words)
F.close()

After this program runs, the file testing.txt will contain:

Replacedmyshoelaceswithearbudsandnowtheytiethemselves.