Need help with file handling

Why the output is empty in the following code

f = open("/storage/emulated/0/Pokemon.txt","w+")
f.write("""A is first letter of Alphabet 
B is second letter of Alphabet
C is third letter of Alphabet
D is fourth letter of Alphabet """)
print(f.readline(), end = "")
print(f.readline(), end = "")
print(f.readline(), end = "")
print(f.readline(), end = ""

Is it cuz of w+ mode, cuz when I tried same with r+ mode it’s working but it’s printing first list again at the end.
This is the code

f = open("/storage/emulated/0/Pokemon.txt","w+")
f.write("""A is first letter of Alphabet 
B is second letter of Alphabet
C is third letter of Alphabet
D is fourth letter of Alphabet """)
print(f.readline(), end = "")
print(f.readline(), end = "")
print(f.readline(), end = "")
print(f.readline(), end = "")

And this is output

A is first letter of Alphabet
B is second letter of Alphabet
C is third letter of Alphabet
D is fourth letter of Alphabet A is first letter of Alphabet

[Program finished]

Also I noticed a glitch
If I replace w+ with r+ and run the code it gives this output

A is first letter of Alphabet
B is second letter of Alphabet
C is third letter of Alphabet
D is fourth letter of Alphabet

and run again the same code it prints first line again at the end.

You’re writing to the file and then reading from it where it left off, without resetting/rewinding the file position. Try setting the file position back to the start with f.seek(0).

1 Like

sorry for asking silly questions and thank you for helping

It’s a combination of a couple of things. First, if you look at your txt file, you’ll see that’s simply what the fourth line looks like.

So why is that? The string you write has a few newlines inside, but none at the end. So the first time it’s written to the file, the fourth line looks normal, but has no newline.

When you run the program again (with r+), the contents are written at the end. But since the newline is missing, the first line written is not separated from the previous last line. So the two get smushed together on the fourth line.

1 Like

I noticed now I was opening file from wrong path, they both got same name