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

1st Sep 2020, 5:43 PM
Ehsan Asadzadeh
Ehsan Asadzadeh - avatar
4 Answers
+ 3
Ehsan Asadzadeh Try f.readlines() or readline() method
1st Sep 2020, 6:07 PM
Ajith
Ajith - avatar
+ 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.
1st Sep 2020, 6:11 PM
Ipang
+ 2
*note: it works, but prints a blank line instead of "hello!"
1st Sep 2020, 5:51 PM
Ehsan Asadzadeh
Ehsan Asadzadeh - avatar
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.
1st Sep 2020, 6:04 PM
Ehsan Asadzadeh
Ehsan Asadzadeh - avatar