0

When attempting to read a file in python it seems to print out just a space instead of "Test Message" here's my code:

contents = "Test Message"

def readAndWritetofile():
    with open("file.txt", 'w+') as file:
        file.write(contents)
        print(file.read())

    
    
readAndWritetofile()
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
  • ```file.seek(0)```- before ```print(file.read())``` –  Jul 27 '21 at 05:27
  • Try: https://stackoverflow.com/questions/16208206/confused-by-python-file-mode-w –  Jul 27 '21 at 05:29
  • Does this answer your question? [Confused by python file mode "w+"](https://stackoverflow.com/questions/16208206/confused-by-python-file-mode-w) –  Jul 27 '21 at 05:32

3 Answers3

1

you forgot

file.seek(0)

before line 6

1

After the write the file pointer is at the end of the file. You can seek back to the start or reopen.

contents = "Test Message"

def readAndWritetofile():
    with open("file.txt", 'w+') as file:
        file.write(contents)
        file.seek(0)
        print(file.read())

readAndWritetofile()

or

contents = "Test Message"

def readAndWritetofile():
    with open("file.txt", 'w') as file:
        file.write(contents)
        # exit the with closes the file
    with open("file.txt") as file:
        print(file.read())

readAndWritetofile()
tdelaney
  • 73,364
  • 6
  • 83
  • 116
0

You should add file.seek(0). If you forget this, the file.read() call will try to read from the end of the file, and will return an empty string.

Currently, the pointer is at the end of the file. file.seek(0)moves it to the start of the file.

contents = "Test Message"

def readAndWritetofile():
    with open("file.txt", 'w+') as file:
        file.write(contents)
        file.seek(0)
        print(file.read())

readAndWritetofile()