user15124295
user15124295

Reputation:

Attempting to write to file spits out nothing

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()

Upvotes: 0

Views: 100

Answers (3)

user15801675
user15801675

Reputation:

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()

Upvotes: 0

tdelaney
tdelaney

Reputation: 77407

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()

Upvotes: 1

MundaneHassan
MundaneHassan

Reputation: 146

you forgot

file.seek(0)

before line 6

Upvotes: 1

Related Questions