for word in keys:
out.write(word+" "+str(dictionary[word])+"\n")
out=open("alice2.txt", "r")
out.read()
For some reason, instead of getting a new line for every word in the dictionary, python is literally printing \n between every key and value. I have even tried to write new line separately, like this...
for word in keys:
out.write(word+" "+str(dictionary[word]))
out.write("\n")
out=open("alice2.txt", "r")
out.read()
What do I do?
Suppose you do:
And then you do:
It appears that Python has just written the literal
\n
in the file. It hasn't. Go to the terminal:The Python interpreter is showing you the invisible
\n
character. The file is fine (in this case anyway...) The terminal is showing the__repr__
of the string. You canprint
the string to see the special characters interpreted:Note how I am opening and (automatically) closing a file with
with
:It appears in your example that you are mixing a file open for reading and writing at the same time. You will either confuse yourself or the OS if you do that. Either use
open(fn, 'r+')
or first write the file, close it, then re-open for reading. It is best to use awith
block so the close is automatic.