Search code examples
pythonfileio

Script doesn't read file


I have a problem with the read() function in Python, it just doesn't read the file:

with open("D:\\Joseph\\pythontest.txt", "w+") as f:
 f.write("Hello World")
 print(f.read())

It doesn't show anything in the output (not even an error), just finishes the program.

screenshot of code in Sublime IDE showing nothing printed


Solution

  • You are writing to the file, but you didn't go back in the file. The "cursor" is located after what you wrote.

    Try f.seek(0) to go at the beginning of your file after writing to it.