How do I make a space between words when writing to a text file in python

user3662438 picture user3662438 · Jan 7, 2015 · Viewed 39.7k times · Source

The following code writes to a text file

if classno== '1':
    f = open("class1.txt", "a")
if classno== '2':
    f = open("class2.txt", "a")
if classno== '3':
    f = open("class3.txt", "a")
f.write(name) 
f.write(score)
f.close()

However, in the text file the name and score do not have space between them for example, how could I change "James14" in to "James 14"

Answer

Bhargav Rao picture Bhargav Rao · Jan 7, 2015

You can try

f.write(name) 
f.write(' ') 
f.write(score)

Or

f.write(name + ' ') 
f.write(score)

Or

f.write(name ) 
f.write(' ' +score)

Or

f.write("{} {}".format(name,score)) 

Or

f.write("%s %s"%(name,score)) 

Or

f.write(" ".join([name,score]))