How to make space between words when writing to 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 a text file, the name and the score do not have a place in between, for example how can I change "James14" to "James 14"
source to share
You will need to write this 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 are using from __future__ import print_function
, you can also use a function print()
and add its space for you:
print(name, score, file=f, end='')
I set end
to empty string because otherwise you will also get a newline character. Of course, you may need this newline character if you are writing multiple names and evaluations to the file and each entry must be on a separate line.
source to share
You have to format the string.
output = "%(Name)s %(Score)s" %{'Name': name, 'Score':score}
f.write(output)
f.close()
Basically,% (Name) s is a placeholder (denoted by%) for the string (denoted by s following the parentheses) that we will refer to as "Name". After our format string, which is wrapped in "", we have this weird thing:
% {'Name': name, 'Score': score}
It is a dictionary that provides replacement for the "Name" and "Score" placeholders.
source to share