user3662438
user3662438

Reputation: 121

How do I make a space between words when writing to a text file in 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"

Upvotes: 9

Views: 62410

Answers (5)

Martijn Pieters
Martijn Pieters

Reputation: 1121594

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.

Upvotes: 7

Cassandra
Cassandra

Reputation: 175

Bhargav and Martjin's answers are good. There are many ways to do it. I'd like to add that the .format way seems to be a little better because you can potentially reuse the arguments and organize your code better.

Upvotes: 2

Mitchell Gouzenko
Mitchell Gouzenko

Reputation: 129

You should format a string.

output = "%(Name)s %(Score)s" %{'Name': name, 'Score':score}
f.write(output)
f.close()

Basically, %(Name)s is a placeholder (denoted by the %) for a string (denoted by the s following the parentheses), which we will reference by "Name". Following our format string, which is wrapped in "", we have this weird thing:

%{'Name': name, 'Score':score}

This is a dictionary that provides replacements for the "Name" and "Score" placeholders.

Upvotes: 0

Cory Kramer
Cory Kramer

Reputation: 117856

A simple way would be to simply concatenate with a space character

f.write(name + ' ' + score)

A more robust method (for if the formatting gets more involved) is to use the format method

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

Upvotes: 5

Bhargav Rao
Bhargav Rao

Reputation: 52071

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]))

Upvotes: 13

Related Questions