Newline “\n” not Working when Writing a .txt file Python

后端 未结 1 1350
面向向阳花
面向向阳花 2021-01-22 07:30
for word in keys:
    out.write(word+\" \"+str(dictionary[word])+\"\\n\")
    out=open(\"alice2.txt\", \"r\")
    out.read()

For some reason, instead o

相关标签:
1条回答
  • 2021-01-22 08:13

    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.

    0 讨论(0)
提交回复
热议问题