+ 1
Why this happening(print)
Why I can't print the content of this text file properly? with open("newfile.txt", "r+") as f: f.write("hello!") print(f.read())
4 Answers
+ 3
Ehsan Asadzadeh
Try f.readlines() or readline() method
+ 3
Try to move file cursor to the beginning of file just before printing the file content. The cursor points to the end of the file after writing into the file.
f.seek(0) # go to beginning of file
print(f.read()) # now read
NOTE: You will need to create the file first if you were to work in Code Playground. Directly opening a file as in the attached snippet will trigger an error.
+ 2
*note: it works, but prints a blank line instead of "hello!"
0
Ajith
With adding f.close() at the end of code, yes it works.But it prints the initial contents,but not the new contents:
If we change "hello!" to "goodbye!", it doesn't print any "goodbye!" at all.