Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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"

like image 936
user3662438 Avatar asked Jan 07 '15 18:01

user3662438


People also ask

How do you put a space in a text file?

Press the "Enter" or "Return" key on your computer keyboard to insert a space between the lines or blocks of text. You can insert as many paragraph spaces as you want by pressing the key more than once.


2 Answers

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]))
like image 166
Bhargav Rao Avatar answered Sep 19 '22 12:09

Bhargav Rao


You'll have to write that space:

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

or use string formatting:

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

If you are using Python 3, or used from __future__ import print_function, you could also use the print() function, and have it add the space for you:

print(name, score, file=f, end='')

I set end to an empty string, because otherwise you'll also get a newline character. Of course, you may actually want that newline character, if you are writing multiple names and scores to the file and each entry needs to be on its own line.

like image 21
Martijn Pieters Avatar answered Sep 21 '22 12:09

Martijn Pieters