+ 1

Why is it printing xt? And what should I correct?

file = open("newfile.txt", "w") file.write("Some new text") file.close() file = open("newfile.txt", "r+") file.write("hello world") print("Reading new contents") print(file.read()) print("Finished") file.close() #why is it printing xt ?

24th Feb 2021, 2:22 AM
Prabesh Guragain
Prabesh Guragain - avatar
7 odpowiedzi
+ 1
Remember you wrote "Some new teXT"? There the XT comes from.
24th Feb 2021, 6:18 AM
Tomas Konecny
+ 3
If you don't want to overwrite the contents, open the file with "a" (for append) rather than "w" then your cursor will be at the end rather than at the beginning. If you are appending, you might want to start with "\n".
24th Feb 2021, 4:49 AM
David Ashton
David Ashton - avatar
+ 2
I'm not sure about that, but it looks like you override old text, and then you point to the end of new text, so you have "hello worldxt" in your file, with cursor before "xt". Then you use file.read(),which reads everything after cursor. I have no idea if I'm right, it just looks like that
24th Feb 2021, 2:28 AM
Michal Doruch
+ 1
your file content after overwriting the existing file is : hello worldxt Now, written = f.write(data) advances the position by written bytes so f.write('abc') moves the cursor pointer to current + len('abc') you can put a f.tell() to know the current position . in you case file.tell() would give 11. In the end , f.read() reads the file from this position till EOF.
24th Feb 2021, 3:18 AM
Hima
Hima - avatar
+ 1
Thanks
24th Feb 2021, 3:54 AM
Prabesh Guragain
Prabesh Guragain - avatar
+ 1
Length of the string "Some new text" is 13, while length of "hello world" is only 11. So when you are opening the file for second time, your script starts overwriting the previous string "Some new text". But because "hello world" is 2 letters shorter than "Some new text", it stops overwriting it at the 11th letter, which means it stops here "Some new te|xt" ("|" is my mark of the place where it stops)... That's why the result is "hello world|xt"
24th Feb 2021, 6:25 AM
Tomas Konecny
0
Ya for sure I have overwritten but I am also confused fron where xd came. Thanks for your answer
24th Feb 2021, 2:43 AM
Prabesh Guragain
Prabesh Guragain - avatar