2
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?

Julien
  • 13,986
  • 5
  • 29
  • 53
  • Are you sure your words dont contain `\n` in them, as a side note why are you not closing your file before opening another? – Nick is tired Jun 07 '17 at 01:01
  • 3
    There's a lot wrong here. You're writing then opening? – erip Jun 07 '17 at 01:02
  • Are you visualizing the result in the python shell or in the txt file (using a standard text editor), I'm pretty sure the result will be as you expect in the latter... – Julien Jun 07 '17 at 01:03
  • Why are you re-opening your file, and how do you expect to write to it when you reach the next `word` in `keys` when you've opened it in `r` mode? – zwer Jun 07 '17 at 01:07

1 Answers1

6

Suppose you do:

>>> with open('/tmp/file', 'w') as f:
...    for i in range(10):
...       f.write("Line {}\n".format(i))
... 

And then you do:

>>> with open('/tmp/file') as f:
...    f.read()
... 
'Line 0\nLine 1\nLine 2\nLine 3\nLine 4\nLine 5\nLine 6\nLine 7\nLine 8\nLine 9\n'

It appears that Python has just written the literal \n in the file. It hasn't. Go to the terminal:

$ cat /tmp/file
Line 0
Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9

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 can print the string to see the special characters interpreted:

>>> s='Line 1\n\tLine 2\n\n\t\tLine3'
>>> s
'Line 1\n\tLine 2\n\n\t\tLine3'
>>> print s
Line 1
    Line 2

        Line3

Note how I am opening and (automatically) closing a file with with:

with open(file_name, 'w') as f:
  # do something with a write only file
# file is closed at the end of the block

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 a with block so the close is automatic.

dawg
  • 98,345
  • 23
  • 131
  • 206