Reputation:
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
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
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