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"
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.
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]))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With