Search code examples
pythonpython-3.xioosx-mavericks

No line outputted in Python


When I run the following code, instead of outputting text, it just displays a new line.

f = open('log.txt', 'a+')

nick = raw_input('Choose a nickname: ')
print('Your nickname is now ' + nick)


f.write(nick + ' has joined the room.\n')
print f.read()

When I look in log.txt, it has the correct text in it.


Solution

  • When you open a file as "a+", you're specifically pointing the computer at the last line of the file and telling it "Start reading from here." That's why you're able to append to it, since it's not going to write over anything starting from the end.

    That's also why calling f.read() won't find anything. If you have the text:

    File: foo.txt
    Body:
    Nick has joined the room.
    Dave has joined the room.
    Sally has joined the room.
    

    But when you open the file, you open it after that last period, all you'll read is:

    ''
    

    To solve this, use seek.

    f = open('foo.txt','a+') # better to use a context manager!
    f.write("bar.\nspam.\neggs.")
    f.read()
    >> ''
    f.seek(0) # moves the pointer to the beginning of the file
    f.read()
    >> bar.
    >> spam.
    >> eggs.